首页 > 解决方案 > return new futureBuilder 在屏幕尺寸更改时不断向服务器请求

问题描述

我正在构建一个应用程序,它有一个从服务器请求数据的底部栏,当我更改屏幕大小时,它再次向服务器请求

这是我的底部栏小部件

Widget bottomNavigationBar() {
  return new BottomAppBar(
    color: const Color(0xFF1E90FF),
    child: new Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children:[
        Container(
          padding: EdgeInsets.only(left: 20),
          child: futureBuilderWidget(setVersion())
        ),
        Container(
          child: Text(
              DateFormat('yyyy-MM-dd hh:mm:ss').format(DateTime.now()),
              style: TextStyle( fontSize: 16, color: const Color(0xffebebeb))
          ),
        ),
       
      ],
    ),
  );
}

这是我的 futureBuilder 小部件

  Widget futureBuilderWidget(_future) {
    return new FutureBuilder<dynamic>(
      future: _future,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return Text(
              snapshot.error.toString(),
              style: TextStyle(fontSize: 16, color: const Color(0xffebebeb)),
            );
          } else if (snapshot.hasData) {
            return Text(snapshot.data,
              style: TextStyle(fontSize: 16, color: const Color(0xffebebeb)),
            );
          }
        }
        return CircularProgressIndicator();
      },
    );
  }

无论如何,我可以问一次吗?

标签: flutterdart

解决方案


将 future 放入 init() 状态。我希望它只会运行一次。PS:不要把它放在 setState() 中,它会在每次屏幕重新生成时运行。


推荐阅读