如何防止在Flutter中重建有状态的小部件

时间:2019-12-15 18:15:13

标签: flutter dart flutter-navigation

我正在从api(屏幕1)加载数据,并单击该项目,然后使用新的有状态小部件打开一个新屏幕(屏幕2)。但是现在当我从屏幕2按向后箭头时,我可以看到屏幕1,但它再次调用api。当我们从屏幕2回到屏幕1时,我不想这么做。

屏幕1代码:

  class Screen1 extends StatefulWidget {
      @override
      _Screen1State createState() => _Screen1State();
    }

    class _Screen1 State
        extends State<Screen1> with AutomaticKeepAliveClientMixin<Screen1>
    {


      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: getdata(), //api calling
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                // TODO: Handle this case.
                case ConnectionState.waiting:
                  //my code
                case ConnectionState.active:
                // TODO: Handle this case.
                case ConnectionState.done:
                  if (snapshot.connectionState == ConnectionState.done) {
                    return showdata(snapshot.data);
                  }
              }
            });
      }

  Widget showdata(Response data) {
    return ListView.builder(
        itemCount: 1,
        itemBuilder: (BuildContext context, int index) {
          return Container(
              decoration: BoxDecoration(color: Colors.white),
              child: ListTile(
                onTap: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (_) => Screen2()));
                },
              )
          );
        });

      @override
      // TODO: implement wantKeepAlive
      bool get wantKeepAlive => true;
    }

屏幕2:

class Screen2 extends StatefulWidget {
  @override
  _Screen2State createState() => _Screen2State();
}

class _Screen2State extends State<Screen2> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

从屏幕2返回时如何防止再次重建屏幕1?

0 个答案:

没有答案