flutter - 为什么我的 FutureBuilder 尽管充满了等待,但仍然不工作?

标签 flutter dart

我正在使用LiveTv应用程序。每次尝试使用API​​加载应用程序时,都会显示“RangeError(索引):无效值:有效值范围为空:0”。因此我了解到,因为在加载应用程序时未加载数据,因此出现错误。
所以我使用了一个叫做Future Builder的东西,但是尽管如此,我仍然遇到相同的错误,但是在加载之后的某个时候,我尝试放置计数器,因为同样需要花费一些时间来构建for循环,但是仍然会发生相同的错误我只是不知道我要去哪里错了
下面是代码,下面是我插入的每个代码的简短说明,请看一下:

Widget build(BuildContext context) {
    Widget widgetOptions(int idx) {
      Widget _selectedWidget = CircularProgressIndicator();
      switch (idx) {
        case 0:
          _selectedWidget = homePageForBottomNavigator();
          break;
        case 1:
          _selectedWidget = MoviesPageForBottomNavigator();
          break;
        case 2:
          _selectedWidget = TvSHowsPageOfBottomNavigator();
          break;
        case 3:
          _selectedWidget = MusicPageofBottomNavigator();

          break;
        case 4:
          _selectedWidget = NewsPageOfBottomNavigator();

          break;
        case 5:
          _selectedWidget = LifeStylePageOfBottomNavigator();
          break;
        case 6:
          _selectedWidget = SportsPageOfBottomNavigator();
      }
      return _selectedWidget;
    }

    return Scaffold(
      //   key: _drawerKey,
         body: SafeArea(
        child: SingleChildScrollView(
            controller: _scrollController,
            child: FutureBuilder(
                future: widgetLoadingFunctions(_selectedIndex),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.hasData != null) {
                    return widgetOptions(_selectedIndex);
                  } else
                    return CircularProgressIndicator();
                })),
      ),
      drawer: Drawer(),
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.black,
        showUnselectedLabels: true,
        type: BottomNavigationBarType.shifting,
        currentIndex: _selectedIndex,
        fixedColor: Colors.amber,
        onTap: (int index) {
          setState(() {
            _selectedIndex = index;
          });
        },
        items: <BottomNavigationBarItem>[
//          Icon(
//            FontAwesome.facebook_square,
//            color: Colors.amber,
//          ),
          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(
              MaterialCommunityIcons.video_vintage,
            ),
            title: Text(
              'Movies',
            ),
          ),
          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(Icons.live_tv),
            title: Text(
              'Tv shows',
            ),
          ),

          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(Icons.music_video),
            title: Text(
              'Music',
            ),
          ),
          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(Icons.radio),
            title: Text(
              'News',
            ),
          ),
          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(
              FontAwesome.heartbeat,
            ),
            title: Text(
              'LifeStyle',
            ),
          ),
          BottomNavigationBarItem(
            backgroundColor: Colors.black,
            icon: Icon(
              Ionicons.md_football,
            ),
            title: Text(
              'Sports',
            ),
          ),
        ],
      ),
    );
   }
}
因此,在上面的代码中有一个底部的导航栏,其selected_index指示必须加载哪个异步函数,然后必须加载相应的小部件。我将在下面的异步函数中以及 future 的相应switch语句中放入。
Future widgetLoadingFunctions(int idx) async {
    var _selectedFunxtion;
    switch (idx) {
      case 0:
        _selectedFunxtion = await functionsToBeLoadedForHomePage();
        break;
      case 1:
        _selectedFunxtion = //yet to be implemented
        break;
      case 2:
        _selectedFunxtion =  //yet to be implemented
        break;
      case 3:
        _selectedFunxtion = //yet to be implemented

        break;
      case 4:
        _selectedFunxtion = //yet to be implemented

        break;
      case 5:
        _selectedFunxtion =  //yet to be implemented
        break;
      case 6:
        _selectedFunxtion = //yet to be implemented
    }
    return _selectedFunxtion;
  }
这是异步功能:
Future functionsToBeLoadedForHomePage() async {
    int counter = 10;
    String url =
        "https://livetvapi.apyhi.com/api/v3/home?pageLocation=home&countries=IN&app_version=13&"
        "user_id=44edc2c905ae163f&package_id=livetv.movies.freemovies.watchtv.tvshows&os_platform=android";

    var res = await http
        .get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});

    if (res.statusCode == 200) {
      final _homePage = homePageFromJson(res.body);

      for (var homeBannerObject in _homePage.homeBanners) {
        setState(() {
          _homeBannerObjectMovieIdList.add(homeBannerObject.movieId);
          counter = counter - 1;
        });
      }

      for (var homeBannerObject in _homePage.movies) {
        setState(() {
          _popularMoviesMovieId.add(homeBannerObject.movieId);
          counter = counter - 1;
        });
      }

      for (var homeBannerObject in _homePage.series) {
        setState(() {
          _seriesData.add(homeBannerObject.posterLink);
          counter = counter - 1;
        });
      }

      for (var homeBannerObject in _homePage.musicCategories) {
        setState(() {
          _musicCategories.add(homeBannerObject.categoryName);
          counter = counter - 1;
        });
      }

      for (var playListObj in _homePage.musicPlaylists.playlists) {
        setState(() {
          _musicCategories.add(playListObj.playlistName);
          counter = counter - 1;
        });
      }

      for (var publisherObj in _homePage.publishers) {
        setState(() {
          _popularNewsChannelNames.add(publisherObj.fullName);
          counter = counter - 1;
        });
      }
      for (var publisherObj in _homePage.publishers) {
        setState(() {
          _popularNewsChannelProfilePicUrl.add(publisherObj.profilePicUrl);
          counter = counter - 1;
        });
      }
      for (var liveChannelObj in _homePage.liveChannels) {
        setState(() {
          _liveNewsChannelProfilePicUrl.add(liveChannelObj.publisherProfilePic);
          counter = counter - 1;
        });
      }
      for (var liveChannelObj in _homePage.liveChannels) {
        setState(() {
          _liveNewsChannelNames.add(liveChannelObj.publisherName);
          counter = counter - 1;
        });
      }
      setState(() {
        _musicPlaylistThemeName = _homePage.musicPlaylists.categoryName;
        counter = counter - 1;
        return counter == 0 ? "Successfully Exectued" : null;
      });
    } else
      return null;
// print("finished services...........................");
  }
我已放入计数器,以便在所有列表加载完毕后变为0,并返回非null值
最终将被调用的小部件如下:
  Widget homePageForBottomNavigator() {
    return Stack(
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _buildBody(MediaQuery.of(context).size.height * 0.35,
                _homeBannerObjectMovieIdList),

            HorizontalListView("Popular movies", _popularMoviesMovieId, false),
            HorizontalListView("Popular Tv shows", _seriesData, false),
            //infinite list view to be implemented here
            HorizontalGridViewOfCardsofGradientColorWithtitle(1, "Music"),
//            HorizontalListViewWithoutViewAll(
//                _musicPlaylistThemeName , false),
            HorizontalListViewWitCircularCards("Popular News channels",
                _popularNewsChannelProfilePicUrl, _popularNewsChannelNames),
            HorizontalListViewWithoutViewAllForLiveNewsChannels(
                "Live News Channels",
                _liveNewsChannelProfilePicUrl,
                _liveNewsChannelNames),

            //VerticalListView(["Latest News"],false),
          ],
        ), //end of 1st Widget
        Positioned(
            bottom: MediaQuery.of(context).size.height * 0.01,
            left: MediaQuery.of(context).size.width * 0.3,
            child: returnToTopButton()),
      ],
    );
  }
以上3个片段已在有状态窗口小部件的状态对象的构建功能之前编写

最佳答案

在FutureBuilder中,您有错误的条件,(snapshot.hasData!= null)始终为true,应该是这样的:

FutureBuilder(
                future: widgetLoadingFunctions(_selectedIndex),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.hasData) {
                    return widgetOptions(_selectedIndex);
                  } else
                    return CircularProgressIndicator();
                })),
或像这样:
FutureBuilder(
                future: widgetLoadingFunctions(_selectedIndex),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data != null) {
                    return widgetOptions(_selectedIndex);
                  } else
                    return CircularProgressIndicator();
                })),

关于flutter - 为什么我的 FutureBuilder 尽管充满了等待,但仍然不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63846698/

相关文章:

dart - 如何将 CSS 类绑定(bind)到 Polymer 中的可观察对象或属性?

flutter - 强制加载所有窗口小部件

laravel - 使用 Laravel 进行 Flutter FCM

dart - Matrix4 参数在间接传递给 Transform 时表现不同

flutter - 在容器 flutter 处制作渐变效果,

git - VSCode Flutter - 停止跟踪 Flutter 存储库更改

javascript - 在 Flutter Web 中扫描二维码的可能性

android - 找不到 com.google.firebase-core :17. 0.1:

android - 如何从 Flutter 中的 Android java Activity 调用 Dart 方法?

javascript - 我可以在Android应用程序中使用javascript吗?