我使用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);
}
observations.dart:
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'],
);
}
}
感谢您的帮助:)
答案 0 :(得分:1)
在这种情况下,您必须将itemCount
设置为要在ListView
中遍历的列表的长度。
我看到您正在使用 user.myFollows [i]
所以也许您应该使用:
itemCount: user.myFollows.length,