addOne() {
setState(() {
total++;
});
}
부모 state 의 total 을 변경하려고 setState 블록안에서 total++을 실행아면 아래와 같은 에러가 발생합니다.
정확히는 다이얼로그를 띄우려고 플로팅 버튼을 클릭시 발생합니다.
setState를 제거하면 에러는 발생하지 않습니다.
전체 코드 첨부합니다.
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(home: MyAppState())
);
}
class MyAppState extends StatefulWidget {
const MyAppState({Key? key}) : super(key: key);
@override
State<MyAppState> createState() => _MyAppStateState();
}
class _MyAppStateState extends State<MyAppState> {
var total = 3;
var names = ["김영숙", "홍길동", "피자집"];
List<dynamic> likes = [0, 0, 0];
addOne() {
setState(() {
total++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (c) {
return DialogUi(addOne: addOne());
});
},
child: Text("dialog"),
),
appBar: AppBar(title: Text(total.toString())),
);
}
}
class DialogUi extends StatelessWidget {
const DialogUi({Key? key, this.addOne}) : super(key: key);
final addOne;
@override
Widget build(BuildContext context) {
return Dialog(
child: Container(
padding: EdgeInsets.all(20),
width: 300,
height: 300,
child: Column(
children: [
TextField(),
TextButton(onPressed: () {
addOne();
}, child: Text('완료')),
TextButton(onPressed: () {
Navigator.pop(context);
}, child: Text('취소'))
],
),
),
);
}
}