使用Navigator.push()时出现“无限循环”

时间:2020-02-14 16:58:08

标签: flutter

我尝试使用Navigator.push()方法加载另一页,但是当我这样做时,它在浏览页面时抛出错误,然后重新启动页面加载并显示错误,然后再次加载,再次出现错误...

以下是导航代码:

return Future.delayed(Duration.zero, (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserProfilePage(id, cookies)));
});

其中id是我的用户ID,cookies是字符串列表。

抛出的错误是:

RangeError(索引):无效值:有效值范围为空:0 另请参阅:https://flutter.dev/docs/testing/errors

无效的参数 另请参阅:https://flutter.dev/docs/testing/errors

以下是到达UserProfilePage时调用的方法:

_getUserProfile(BuildContext context, String userId) async
{
await HibooksApiController.getUserInfo(userId).then((response) {
  setState(() {
    var resultApi = json.decode(response.body);
    User result = User.fromJson(resultApi);
    user = result;
  });
});

for (var friend in user.friends) {
  _getFriendProfile(context, friend.id, friends);
}
}

_getFriendProfile(BuildContext context, String friendId, List<User> friends) async
{
await HibooksApiController.getUserInfo(friendId).then((response) {
  setState(() {
    var resultApi = json.decode(response.body);
    User result = User.fromJson(resultApi);
    friends.add(result);
  });
});
}

_getLibraries(BuildContext context, String userId) async
{
await HibooksApiController.getLibraries(userId).then((response){
  setState(() {
    var resultApi = json.decode(response.body);
    for (var item in resultApi) {
      Library library = Library.fromJson(item);
      libraries.add(library);
    }
  });
});
}

2 个答案:

答案 0 :(得分:0)

@MarianoZorrilla我使用发现的示例实现了片段管理器,以下是交互:

_getDrawerItemWidget(int pos){
switch (pos) {
  // SIDEBAR
  case 0:
    return new Text("Nous");
  case 1:
    return new Text("Paramètes");
  case 2:
    return new Text("Langue");
  case 3:
    return new Text("Dictionnaire");
  case 4:
    return new Text("FAQ");
  case 5:
    return new Text("Politique de confidentialité");
    // --- HERE IS MY NAVIGATION PROBLEM --- //
  case 6:
      return Future.delayed(Duration.zero, (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserProfilePage(id, cookies)));
      });
    // --- //
  case 7:
    return new Text("Informations du compte");
  case 8:
    return new Text("Mes Favoris");
  case 9:
    return Future.delayed(Duration.zero, () => Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage())));

  //BOTTOM NAVIGATION BAR
  case 10:
    return new AccueilFragment(id);
  case 11:
    return new LibraryFragment(id, cookies);
  case 12:
    return new ChatFragment(id, cookies);
  case 13:
    return new MatchFragment(id, cookies);
  case 14:
    return new Text("Événements");


  default:
    return new Text("Error");
}
}

方法:

 _onSelectItem(int drawerIndex) {
  setState(() => _selectedDrawerIndex = drawerIndex);
  Navigator.of(context).pop(); // close the drawer
 }

实现:

var drawerOptions = <Widget>[];
drawerOptions.add(
  new SizedBox(
    height: 80,
    width: 350,
    child: new DrawerHeader(
      child: Text("Outils", style: TextStyle(fontFamily: "SFProDisplay")),
      decoration: BoxDecoration(color: Color.fromRGBO(247, 247, 247, 1.0)),
    ),
  )
);
for (var i = 0; i <= 5; i++) {
  var d = widget.drawerItems[i];
  drawerOptions.add(
    new ListTile(
      leading: new SizedBox(child: d.icon,),
      title: new Text(d.title, style: TextStyle(fontFamily: "SFProDisplay")),
      selected: i == _selectedDrawerIndex,
      onTap: () => _onSelectItem(i),
    )
  );
}
drawerOptions.add(
  new SizedBox(
    height: 80,
    width: 350,
    child: new DrawerHeader(
      child: Text("Profil", style: TextStyle(fontFamily: "SFProDisplay")),
      decoration: BoxDecoration(color: Color.fromRGBO(247, 247, 247, 1.0)),
    ),
  )
);
for(var j = 6; j <= 9; j++)
{
  var d2 = widget.drawerItems[j];
  drawerOptions.add(
    new ListTile(
      leading: new SizedBox(child: d2.icon,),
      title: new Text(d2.title, style: TextStyle(fontFamily: "SFProDisplay")),
      selected: j == _selectedDrawerIndex,
      onTap: () => _onSelectItem(j),
    )
  );
}

for (var i = 10; i < widget.drawerItems.length; i++) {
  var d = widget.drawerItems[i];
  navbarOptions.add(
    new BottomNavigationBarItem(
      icon: new SizedBox(child: d.icon,),
      title: Text(d.title),
    )
  );
}

if(navbarOptions.length != 0)
{
  for(var z = navbarOptions.length; z > 5; z--)
  {
    navbarOptions.removeLast();
  }
}

然后在我的Widget build()中调用:

return new Scaffold(
  appBar: new AppBar(
    leading: Builder(builder: (BuildContext context) {
      return new GestureDetector(
        onTap: (){
          Scaffold.of(context).openDrawer();
        },
        child: Material(
          shape: CircleBorder(),
          child: ClipOval(
            child: FadeInImage(
              placeholder: new ExactAssetImage("assets/Pictogramme-fond-blanc.png", scale: 4.5), 
              image: NetworkImage(user.image.url), 
              height: 50, 
              width: 50, 
              fit: BoxFit.cover,
            ),
          ),

        )
      );
    }),
    title: Text(
      user.name.first != "" || user.name.last != "" ? "${user.name.first} ${user.name.last[0]}." : "${user.username}", 
      style: TextStyle(color: Colors.black),
    ),
    backgroundColor: Color(0xFFFFFFFF),
  ),
  drawer: new Drawer(
    child: new SingleChildScrollView(
      child: new Column(
        children: <Widget>[
          new Column(children: drawerOptions),
        ],
      ),
    ),
  ),
  body: _getDrawerItemWidget(_selectedDrawerIndex),

  bottomNavigationBar: BottomNavigationBar(
    items: navbarOptions,
    currentIndex: _selectedNavbarIndex,
    selectedItemColor: hibooks,
    onTap: _onItemTapped,
  ),
);

所有这些方法在我开发它们时都有效,但是当我将Flutter升级到版本“ 1.12.13 + hotfix.5”时,该错误开始了。

答案 1 :(得分:0)

好的,我发现它是Flutter的1.12.13版本存在问题,当我将Flutter SDK升级到1.15时,它解决了我的问题。

谢谢!