我有一个带状态的窗口小部件MyList,其中包含ListView。在任何列表图块上点击时,将打开新屏幕(MyScreen),并且在返回后(通过按左上方的后退按钮)将丢失滚动位置,因为MyList被释放并且initState再次运行。如何防止MyList处置?
class MyList extends StatefulWidget {
@override
_MyListState createState() => new _MyListState();
}
class _MyListState extends State<MyList> {
List<String> items = new List.generate(20, (index) => 'Hello $index');
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Scrollbar(
child: new ListView.builder(
itemBuilder: (context, index) {
return new ListTile(
title: Text(items[index] + ' index $index'),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => new MyScreen(index),
));
},
);
},
itemCount: items.length,
),
),
);
}
}
这是MyScreen:
class MyScreen extends StatefulWidget {
final int indx;
MyScreen(this.indx);
_TaskDetailState createState() => new _TaskDetailState();
}
class _TaskDetailState extends State<MyScreen> {
@override
void initState() {
super.initState();
}
Widget build(context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
title: Text('yoba'),
),
body: Text('yoba ${widget.indx}'),
);
}
}