【发布时间】:2021-08-22 00:32:08
【问题描述】:
当我在子有状态小部件中调用 setState 时。它显示错误或警告。有没有什么方法可以在 Stateful 小部件中调用 Stateful 小部件而不会导致错误或任何好的方法来做同样的事情?
这是我的示例代码:
parent.dart
class Parent extends StatefulWidget {
@override
_ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
var title = "Parent";
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: <Widget>[
Text(title),
Child(init:true), // <-- Calling Child Widget
],
),
),
);
}
}
child.dart
class Child extends StatefulWidget {
final bool init; // <- Showing warning on removing 'final'
// This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: Child.init
Child({
Key? key,
required this.init,
}) : super(key: key);
@override
_ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
@override
Widget build(BuildContext context) {
return Container(
color: widget.init ? Colors.red : Colors.blue,
child: TextButton(
onPressed: () {
setState(
() {
// widget.init = false;
// want to change 'wiget.init' but its final
// removing final causing warning
},
);
},
child: Text("Click me"),
),
);
}
}
【问题讨论】:
标签: flutter flutter-layout flutter-widget