Class 同一Statefulwidget的多个实例似乎共享同一个状态对象?
我正在尝试使用flifter构建一个应用程序,但遇到了一个小问题。我正在尝试实现一个具有三个页面的BottomNavigaOnBar风格的应用程序。(请参见第一个片段)布局使用了三个“ChorePage”类型的对象。似乎应用程序正在创建三个ChorePage实例,但只有一个_ChorePageState实例 这导致变量_dataRows在三个选项卡之间共享,这意味着我不能将不同的信息放入不同的选项卡中。为什么会发生这种情况?我该如何预防 我已将print语句放入createState()函数中,并在PopulateRows函数中打印'this'变量,该函数在每次重新生成ChorePage时都会调用。打印输出如下所示,并确认这三个小部件确实使用相同的状态对象。(对象A只调用一次createState,此变量引用同一对象)Class 同一Statefulwidget的多个实例似乎共享同一个状态对象?,class,flutter,statefulwidget,Class,Flutter,Statefulwidget,我正在尝试使用flifter构建一个应用程序,但遇到了一个小问题。我正在尝试实现一个具有三个页面的BottomNavigaOnBar风格的应用程序。(请参见第一个片段)布局使用了三个“ChorePage”类型的对象。似乎应用程序正在创建三个ChorePage实例,但只有一个_ChorePageState实例 这导致变量_dataRows在三个选项卡之间共享,这意味着我不能将不同的信息放入不同的选项卡中。为什么会发生这种情况?我该如何预防 我已将print语句放入createState()函数中,
今天,我一直在努力解决我认为相同的问题,最终解决方案是将字符串键传递给StatefulWidget构造函数。在你的例子中:
List<Widget> _children = [
new ChorePage(key: Key('A'), Title:'A'),
new ChorePage(key: Key('B'), Title:'B'),
new ChorePage(key: Key('C'), Title:'C')
];
List\u子项=[
新页面(键:键('A'),标题:'A'),
新页面(键:键('B'),标题:'B'),
新页面(键:键('C'),标题:'C'))
];
class ChorePage extends StatefulWidget {
final String Title;
const ChorePage({Key key, this.Title}): super(key: key);
@override
_ChorePageState createState() {
print('Creating: '+this.Title);
return new _ChorePageState();
}
}
class _ChorePageState extends State<ChorePage> {
List<DataRow> _dataRows = [];
@override
Widget build(BuildContext context) {
PopulateRows();
return SingleChildScrollView(
child:Center(
child: DataTable(
columns: [
DataColumn(label: Text(widget.Title.toString())),
DataColumn(label: Text('Col1')),
DataColumn(label: Text('Col2')),
],
rows: _dataRows,
),
),
);
}
void PopulateRows(){
print(this);
print(widget.Title.toString());
//_dataRows = [];
for(int i=0;i<1;i++) {
DataRow R = DataRow(cells:[]);
R.cells.add(DataCell(Text(widget.Title)));
R.cells.add(DataCell(Text(i.toString())));
R.cells.add(DataCell(Text((i + 1).toString())));
_dataRows.add(R);
}
}
}
Installing build\app\outputs\apk\app.apk...
Debug service listening on ws://127.0.0.1:59033/TvJtQ-PN3a8=/ws
Syncing files to device Mi 9T Pro...
I/flutter (28856): Creating: A
I/flutter (28856): _ChorePageState#d1d35
I/flutter (28856): A
I/xxxxxxx.tms_ap(28856): ProcessProfilingInfo new_methods=403 is saved saved_to_disk=1 resolve_classes_delay=8000
I/flutter (28856): _ChorePageState#d1d35
I/flutter (28856): B
I/flutter (28856): _ChorePageState#d1d35
I/flutter (28856): C
List<Widget> _children = [
new ChorePage(key: Key('A'), Title:'A'),
new ChorePage(key: Key('B'), Title:'B'),
new ChorePage(key: Key('C'), Title:'C')
];