我正在使用BottomNavigationBar
显示三个菜单的列表。当用户选择Gallery
时,我呈现了一个Stateful
组件,该组件以其FutureBuilder
方法呈现了build
。这可以按预期工作,但是当用户导航到另一个屏幕时,Gallery
小部件被丢弃,因此我丢失了所有刚获取的图像。如何有效地缓存它们?
home-page.dart
小部件:
final List<Widget> _menuOptions = <Widget>[
Text(
'Schedules',
style: optionStyle
),
Text(
'Stats',
style: optionStyle
),
GalleryPage(key: PageStorageKey('gallery'))
];
void _onMenuSelected(int index){
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context){
//...
body: Center(
child: _menuOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.schedule),
title: Text('Schedules'),
),
BottomNavigationBarItem(
icon: Icon(Icons.satellite),
title: Text('Stats'),
),
BottomNavigationBarItem(
icon: Icon(Icons.image),
title: Text('Gallery'),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onMenuSelected,
)
gallery-page.dart
小部件:
class GalleryPage extends StatefulWidget {
GalleryPage({Key key}) : super(key: key);
@override
_GalleryPageState createState() => _GalleryPageState();
}
class _GalleryPageState extends State<GalleryPage> with AutomaticKeepAliveClientMixin {
Future<List<GalleryImage>> futureGalleryImages;
final AsyncMemoizer _memoizer = AsyncMemoizer();
@override
void deactivate() {
// TODO: implement deactivate
super.deactivate();
print('deactiveating');
}
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
_populateGalleryImages();
}
@override
Widget build(BuildContext context) {
super.build(context);
return FutureBuilder(
future: this.futureGalleryImages,
builder: (BuildContext context, AsyncSnapshot snapshot) {
//...
return _createListView(context, snapshot);
}
},
);
}
Future _populateGalleryImages() {
return this._memoizer.runOnce(() async {
this.futureGalleryImages = GalleryService().fetchGalleryImages();
});
}
我尝试过的事情:
使用AutomaticKeepAliveClientMixin
属性设置为true的wantKeepAlive
混合。但是,这不起作用,因为我的组件始终进入deactive
生命周期,并且始终处于废弃状态。每次都会进行数据获取。我希望使用AsyncMemoizer
如果组件没有被处置。
在实例化组件时使用PageStorageKey
,如上所示。没用。
关于我在做什么错的任何建议?