使用BottomNavigationBar时如何通过屏幕导航缓存FutureBuilder异步结果?

时间:2020-03-21 20:50:10

标签: flutter

我正在使用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();
    });
  }

我尝试过的事情:

  1. 使用AutomaticKeepAliveClientMixin属性设置为true的wantKeepAlive混合。但是,这不起作用,因为我的组件始终进入deactive生命周期,并且始终处于废弃状态。每次都会进行数据获取。我希望使用AsyncMemoizer如果组件没有被处置。

  2. 在实例化组件时使用PageStorageKey,如上所示。没用。

关于我在做什么错的任何建议?

0 个答案:

没有答案