rest - 无效值:Flutter中只有有效值为0:1

标签 rest api flutter dart

我使用FutureBuilder创建了一个UI,以显示来自我的rest api的嵌套对象,但是我不知道为什么,但是在运行我的函数(在我的UI中)后,我的控制台抛出了这种错误:

RangeError (index): Invalid value: Only valid value is 0: 1

我尝试使用flutter doctor,但对我没有帮助,

ps。我不能使用itemCount: snapshot.data.length,因为
Class 'User' has no instance getter 'length'

我的代码:
@override
  void initState(){
    super.initState();
    userApiService = UserApiService();
    _future = getUserData();
  }

  getUserData() async{
    sharedPreferences = await SharedPreferences.getInstance();
    int id = sharedPreferences.getInt('id');
    return userApiService.getUser(id);
  }

  @override
  Widget build(BuildContext context){
    return FutureBuilder(
      future: _future,
      builder: (context, snapshot){
        if(!snapshot.hasData){
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        // User user = snapshot.data;
        return Scaffold(
          backgroundColor: Colors.white,
          body: Container(
            child: ListView.builder(
              itemBuilder: (context, i){
                User user = snapshot.data;
                return GestureDetector(
                  onTap: () {
                    //
                  },
                  child: Container(
                    width: 300,
                    height: 80,
                    color: Colors.blue,
                    child: Text(user.myFollows[i].firstName + ' ' + user.myFollows[i].lastName),
                  ),
                );
              }
            )
          ),
        );
      },
    );
  }

模型用户:
class User {
  List<Observations> followedBy;
  List<Observations> myFollows;
  int id;
  String firstName;
  String lastName;

  User(
      {
      this.followedBy,
      this.myFollows,
      this.id,
      this.firstName,
      this.lastName,
});


  factory User.fromJson(Map<String, dynamic> json){
    return User(
      id: json['id'],
      firstName: json['firstName'],
      lastName: json['lastName'],
      followedBy: parseFollowedBy(json),
      myFollows: parseMyFollows(json),
    );
  }

  static List<Observations> parseFollowedBy(json){
    var lista = json['followedBy'] as List;
    List<Observations> followedByList = lista.map((data) => Observations.fromJson(data)).toList();
    return followedByList;
  }  

  static List<Observations> parseMyFollows(myFollowsJson){
    var list = myFollowsJson['myFollows'] as List;
    List<Observations> myFollowsList = list.map((data) => Observations.fromJson(data)).toList();
    return myFollowsList;
  }

}

List<User> usersFromJson(String jsonData){
  final data = json.decode(jsonData);
  return List<User>.from(data.map((item) => User.fromJson(item)));
}

User userFromJson(String jsonData){
  final data = json.decode(jsonData);
  return User.fromJson(data);
}

String userToJson(User data){
  final jsonData = data.toJson();
  return json.encode(jsonData);
}

模型观察值
class Observations {
  final int id;
  final String firstName;
  final String lastName;

  Observations({this.id, this.firstName, this.lastName});

  factory Observations.fromJson(Map<String, dynamic> parsedJson) {
    return Observations(
      id: parsedJson['id'], 
      firstName: parsedJson['firstName'],
      lastName: parsedJson['lastName'],
      );
  }
}

谢谢你的帮助 :)

最佳答案

在这种情况下,您必须将itemCount设置为要在ListView中遍历的列表的长度。

我看到您正在使用 user.myFollows [i]

因此,也许您应该使用:

itemCount: user.myFollows.length,

关于rest - 无效值:Flutter中只有有效值为0:1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61344884/

相关文章:

json - Grails从请求访问未映射到特定域的JSON属性

python - 如何将 json 加载到 pandas 数据框中?

ruby-on-rails - Rails devise 应用程序为移动应用程序创建 REST api

api - Laravel API 连接多个数据库

flutter - 在不是其子项的 TabBar 上使用 AppBar 样式

javascript - 使用 GitHub API 检查 repo 是否已加星标

java - 调用LockSupport.parkNanos(long)后是否需要检查线程中断状态?

dart - 在 _MaterialAppState 中找不到路由 "home-page"的生成器

Flutter NetworkImage 与 cached_network_image

javascript - 覆盖YouTube的恢复播放功能?