我正在尝试从这个服务器得到一个JSON响应。我是新的flutter,我不知道如何做到这一点。有人能指出我做错了什么吗???
class RESTAPIService{
String apiUrl = "https://mocki.io/v1/048e68cc-9ddb-4aca-8264-6e9f8f273fd2";
Future<List<User>> getUsers() async{
final response = await http.get(Uri.parse(apiUrl));
print(response.body);
if(response.statusCode == 200){
throw getUsersList(response.body);
}else{
throw Exception("Couldn't fetch data");
}
}
List<User> getUsersList(String responseBody){
final parsebody = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsebody.map<User>({(json) => User(name: "", city: "", image: "").fromJson(json)}).toList();
}
}
我做我的转换像贝娄。
class User{
String name;
String city;
String image;
User({required this.name, required this.city, required this.image});
Map<String, dynamic> fromJson(Map<String, dynamic> json){
name = json['name'];
city = json['city'];
image = json['image'];
return json;
}
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['city'] = this.city;
data['image'] = this.image;
return data;
}
}
我在这里调用了json数据。当应用程序运行时,它只显示“Loading...”,不会显示json响应。但我确实从服务器获得了json响应。只是它没有显示在我的应用程序UI中。
child: FutureBuilder(
future: apiService.getUsers(),
builder: (context, snapShot){
if(snapShot.hasData){
return ListView.builder(
itemCount: snapShot.data!.length,
itemBuilder: (context, index){
return InkWell(
onTap: (){
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
blurRadius: 3, spreadRadius: 3,
color: Colors.grey.withOpacity(0.3),
)
]
),
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: ListTile(
title: Text(snapShot.data![index].name ?? '', style: TextStyle(
fontSize: 18, color: Colors.black,
),),
subtitle: Text(snapShot.data![index].city ?? '', style: TextStyle(
fontSize: 15, color: Colors.black,
),),
leading: ClipOval(
child: Image.network(snapShot.data![index].image, fit: BoxFit.cover, width: 60, height: 60,),
),
),
),
);
}
);
}else{
return Container(
child: Center(
child: Text("Loading...", style: TextStyle(
color: Colors.black, fontSize: 15,
)),
),
);
}
},
),`
1条答案
按热度按时间ukqbszuj1#
你的回答是列表,
应该是这样
尝试使用工厂模型,如