【问题标题】:How do I execute FutureBuilder only once in a list that gets reinitialized?如何在重新初始化的列表中只执行一次 FutureBuilder?
【发布时间】:2020-09-09 09:22:44
【问题描述】:

我创建了一个带有底部导航栏的主页的 Flutter 项目。我使用 IndexedStack 作为主体。

我正在尝试使我的 CustomList() 成为显示最新文档的提要。 我也打算用分页。

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  final widgetOptions = [
    CustomList(),
    Page2(),
    Page3(),
    Page4(),
  ];

  int _selectedItemPosition = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(    
      bottomNavigationBar: BottomNavigationBar(
       //
        currentIndex: _selectedItemPosition,
        onPositionChanged: (index) => setState(() {
          _selectedItemPosition = index;
        }),
        items: [
          BottomNavigationBarItem(),
          BottomNavigationBarItem(),
          BottomNavigationBarItem(),
          BottomNavigationBarItem()
        ],
      ),

      body: IndexedStack(
        index: _selectedItemPosition,
        children: widgetOptions,
      ),
    );
  }
}

这是我的 CustomList() 的代码:


class CustomList extends StatefulWidget {

  @override
  _CustomListState createState() => _CustomListState();
}

class _CustomListState extends State<CustomList> {

  @override
  Widget build(BuildContext context) {

    Future<Object> getData()
    {
     //get Data from server
    }


    return FutureBuilder<Object>(
      future: getData(),
      builder: (context, snapshot) {

        if(snapshot.data != null)
        {
          if(snapshot.hasData)
          {
           //get Documents
          }


            return ListView.builder(
              //
              itemBuilder: (context , index) {
                //return a widget that uses the data received from the snapshot
              },
            );
          }

        }

    );
  }
}

问题是,每次我使用底部导航栏更改页面时,每当我使用 CustomList() 返回默认页面时,FutureBuilder 都会再次触发,导致我的列表出现重复。这是因为 CustomList() 再次被初始化。

当我使用 BottomNavigationBar 更改页面时,如何构建我的代码,以便 FutureBuilder 只执行一次并且不会重复触发?

【问题讨论】:

  • 一种方法是使用_HomeState 中的FutureBuilder 来获取数据,然后将其传递给CustomList 小部件。这样你就不会在每次重新构建小部件时调用 API
  • 我已经尝试过了,但 FutureBuilder 仍然会被解雇。
  • 其实我已经把FutureBuilder包裹的CustomList()的整个代码放在了_HomeState的initState()方法中。还是没有解决问题。
  • 你能检查一下这个solution 看看它是否有帮助......我看到的不同之处在于,它不是创建小部件列表,而是从父级传递

标签: firebase flutter google-cloud-firestore


【解决方案1】:

这是因为每次调用 build 时都会获得一个新的未来,因为您将函数调用传递给 FutureBuilder 而不是保持不变的引用。 有几个简单的方法可以解决这个问题。

  1. 您可以存储对未来的引用并将此引用传递给FutureBuilder
  2. 您可以使用async 包中的AsyncMemoizer 只运行一次未来https://api.flutter.dev/flutter/package-async_async/AsyncMemoizer-class.html
  3. 您可以使用provider 包https://pub.dev/documentation/provider/latest/provider/FutureProvider-class.html 中的FutureProvider

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2017-08-10
    相关资源
    最近更新 更多