我用来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,
)
Run Code Online (Sandbox Code Playgroud)
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();
});
}
Run Code Online (Sandbox Code Playgroud)
我尝试过的事情:
使用AutomaticKeepAliveClientMixin
mixin 并将wantKeepAlive
属性设置为 true。然而,这不起作用,因为我的组件总是进入deactive
生命周期并且总是被处置。每次都会发生数据获取。我希望AsyncMemoizer
在该组件没有被处理掉的情况下使用。
PageStorageKey
如上所示,在实例化组件时使用。不工作。
关于我做错了什么有什么建议吗?
归档时间: |
|
查看次数: |
1173 次 |
最近记录: |