Flutter切换到Tab重新加载小部件并运行FutureBuilder

时间:2018-07-07 15:09:10

标签: dart flutter

问题:

我有2个使用“默认标签控制器”的标签,例如:

Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        drawer: Menu(),
        appBar: AppBar(
          title: Container(
            child: Text('Dashboard'),
          ),
          bottom: TabBar(
            tabs: <Widget>[
              Container(
                padding: EdgeInsets.all(8.0),
                child: Text('Deals'),
              ),
              Container(
                padding: EdgeInsets.all(8.0),
                child: Text('Viewer'),
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            DealList(),
            ViewersPage(),
          ],
        ),
      ),
    );
  }
}

DealList()StatefulWidget,其构建方式如下:

Widget build(BuildContext context) {
    return FutureBuilder(
      future: this.loadDeals(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        print('Has error: ${snapshot.hasError}');
        print('Has data: ${snapshot.hasData}');
        print('Snapshot data: ${snapshot.data}');
        return snapshot.connectionState == ConnectionState.done
            ? RefreshIndicator(
                onRefresh: showSomething,
                child: ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: snapshot.data['deals'].length,
                  itemBuilder: (context, index) {
                    final Map deal = snapshot.data['deals'][index];
                    print('A Deal: ${deal}');
                    return _getDealItem(deal, context);
                  },
                ),
              )
            : Center(
                child: CircularProgressIndicator(),
              );
      },
    );
  }
}

使用上述方法,每当我切换回DealList()标签时,就会发生以下情况:重新加载。

Flutter

是否有一种方法可以防止一次完成后重新运行FutureBuilder? (该计划是供用户使用RefreshIndicator重新加载。因此,除非用户明确这样做,否则更改选项卡不会触发任何操作。)

1 个答案:

答案 0 :(得分:36)

这里有两个问题,第一个:

TabController切换选项卡时,它将卸载旧的窗口小部件树以节省内存。如果要更改此行为,则需要将AutomaticKeepAliveClientMixin混入选项卡小部件的状态。

class _DealListState extends State<DealList> with AutomaticKeepAliveClientMixin<DealList> {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context); // need to call super method.
    return /* ... */
  }
}

第二个问题是您对FutureBuilder的使用- 如果您为Future提供新的FutureBuilder,则无法确定结果与上次相同,因此必须重新构建。 (请记住,Flutter最多可以一次调用您的构建方法。)

return FutureBuilder(
  future: this.loadDeals(), // Creates a new future on every build invocation.
  /* ... */
);

相反,您想将Future分配给initState中的State类的成员,然后将此值传递给FutureBuilder。确保以后的重建中的将来是相同的。如果您想迫使国家重新加载交易,则始终可以创建一种方法来重新分配_loadingDeals成员并调用setState

Future<...> _loadingDeals;

@override
void initState() {
  _loadingDeals = loadDeals(); // only create the future once.
  super.initState();
}

@override
Widget build(BuildContext context) {
  super.build(context); // because we use the keep alive mixin.
  return new FutureBuilder(future: _loadingDeals, /* ... */);
}