【问题标题】:FutureBuilder reloading whenever the BottomNavigationBarItem is changed每当更改 BottomNavigationBarItem 时,FutureBuilder 都会重新加载
【发布时间】:2020-06-18 12:24:21
【问题描述】:

我在带有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;
  }

如何保持状态不更新?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    // 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

    【讨论】:

    • 我试过这个,但它总是返回连接状态“无”。 Future 加载后不会更新状态。如果我直接使用“getLessons()”,它可以正常工作
    【解决方案2】:

    问题是我在调用屏幕时没有使用PageView。我在build() 之外启动了4 个屏幕,并在PageView 内将它们全部调用,现在它可以工作了。

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

    【讨论】:

      猜你喜欢
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      相关资源
      最近更新 更多