flutter 每当BottomNavigationBarItem更改时,FutureBuilder重新加载

bmp9r5qi  于 2023-01-06  发布在  Flutter
关注(0)|答案(3)|浏览(143)

我正在使用BottomNavigationBar的屏幕上使用FutureBuilder。但是每当我点击不同的选项卡并返回时,FutureBuilder都会重新加载所有内容。我已经在使用AutomaticKeepAliveClientMixin,我在保存**getLessons()**时遇到问题,因此我不必重新加载它。有人能帮助我吗?

@override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Lesson>>(
        future: getLessons(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.none) {
          } else if (snapshot.connectionState == ConnectionState.waiting) {
          } else {
            return Container();
          }
        });
  }

这是我的getLessons():

Future<List<Lesson>> getLessons() async {
    String url = "...";
    http.Response response = await http.get(url);
    var data = json.decode(response.body);
    (...)
    return lessons;
  }

如何维护状态以避免更新?

tzxcd3kk

tzxcd3kk1#

// Create instance variable
Future myFuture;

@override
void initState() {
  super.initState();

  // assign this variable your Future
  myFuture = getLessons();
}

@override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Lesson>>(
        future: future, // use your future here
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.none) {
          } else if (snapshot.connectionState == ConnectionState.waiting) {
          } else {
            return Container();
          }
        });
  }

贷记CopsOnRoad

r6hnlfcb

r6hnlfcb2#

问题是我在没有使用PageView的情况下调用了屏幕。我在build()之外启动了4个屏幕,并在一个PageView内调用了它们,现在它工作了。

body: PageView(
    controller: _pageController,
    onPageChanged: (index) {
      setState(() {
        _index = index;
      });
    },
    children: [_container1, _container2, _container3, _container4],
  ),
ruoxqz4g

ruoxqz4g3#

如果将PageView替换为PreloadPageView,则不会再次调用FutureBuilder
只需安装preload_page_viewhere

相关问题