【发布时间】:2019-04-05 15:17:53
【问题描述】:
我只是解析复杂的 JSON 并显示在 listView 上以供学习。
1) 模型类
class AllUsers {
final List<User> alluser;
AllUsers({this.alluser});
factory AllUsers.formJson(List<dynamic> jsonArr){
List<User> arruser = jsonArr.map((f)=> User.formJson(f)).toList();
return AllUsers(
alluser: arruser
);
}
}
class User {
int id;
String name;
String email;
Address address;
String phone;
String website;
Company company;
User({this.id, this.name, this.email, this.address, this.phone, this.website, this.company});
factory User.formJson(Map<String, dynamic> jsonObj) {
return User(
id: jsonObj['id'],
name: jsonObj['name'],
email: jsonObj['email'],
address: Address.formJson(jsonObj['address']),
phone: jsonObj['phone'],
website: jsonObj['website'],
company: Company.formJson(jsonObj['company'])
);
}
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({this.street, this.suite, this.city, this.zipcode, this.geo});
factory Address.formJson(Map<String, dynamic> jsonObj) {
return Address(
street: jsonObj['street'],
suite: jsonObj['suite'],
city: jsonObj['city'],
zipcode: jsonObj['zipcode'],
geo: Geo.formJson(jsonObj['geo'])
);
}
}
class Geo {
String lat;
String lng;
Geo({this.lat, this.lng});
factory Geo.formJson(Map<String, dynamic> jsonObj) {
return Geo(
lat: jsonObj['lat'],
lng: jsonObj['lng'],
);
}
}
class Company {
String name;
String catchPhrase;
String bs;
Company({this.name, this.catchPhrase, this.bs});
factory Company.formJson(Map<String, dynamic> jsonObj) {
return Company(
name: jsonObj['name'],
catchPhrase: jsonObj['catchPhrase'],
bs: jsonObj['bs']
);
}
}
2)ViewModel
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:parsejsonlist/All Screens/Home/Model/users.dart';
class UserViewModel {
Future<AllUsers> callWebserviceForFetchUserData() async{
var listOfUser = await http.get('https://jsonplaceholder.typicode.com/users');
List<User> decodedJSON = json.decode(listOfUser.body);
AllUsers arrayOfAlluser = AllUsers.formJson(decodedJSON);
print("arrayOfAlluser $arrayOfAlluser");
return arrayOfAlluser;
}
}
3) 查看部分代码。
import 'package:flutter/material.dart';
import 'package:parsejsonlist/All Screens/Home/Model/users.dart';
import 'package:parsejsonlist/All Screens/Home/ModelView/userviewmodel.dart';
class HomeSceen extends StatefulWidget {
@override
State<StatefulWidget> createState() => HomeScreenState();
}
class HomeScreenState extends State<HomeSceen> {
AllUsers arryOfUser;
UserViewModel userViewmodel;
@override
initState(){
super.initState();
userViewmodel = UserViewModel();
}
callMethodFetchUserData() async {
arryOfUser = await userViewmodel.callWebserviceForFetchUserData();
User userRes = arryOfUser.alluser[0];
print("response === >> ${userRes.company.catchPhrase}");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("JSON Parsing")
),
body: Container(
child: FutureBuilder<AllUsers>(
future: callMethodFetchUserData(),
builder: (context, data){
return setupListView();
},
),
),
);
}
Widget setupListView(){
return ListView.builder(
itemCount: arryOfUser.alluser.length,
itemBuilder: (BuildContext context, int index) {
User userdata = arryOfUser.alluser[index];
setupListTile(userdata);
},
);
}
Widget setupListTile(User userdata){
return ListTile(
leading: CircleAvatar(
backgroundColor: Colors.orangeAccent,
child: Text(userdata.name[0].toUpperCase(),
style: TextStyle(color: Colors.white)),
),
title: Text(userdata.name),
subtitle: Text(userdata.company.name),
);
}
}
所以,我的问题是每次我都因为很多错误而失败。
类型“未来”不是类型“未来”的子类型
我知道有很多错误,但我是 Flutter 的新手。 我哪里错了?如何解决这个问题,请指导我正确的方向。
更新
child: FutureBuilder<List<User>>(
future: userViewmodel.callWebserviceForFetchUserData(),
builder: (BuildContext context, AsyncSnapshot<List<User>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
return setupListView(snapshot.data);
}
return null;
},
Getting Error: "Type List<dynamic> is not a subtype of type List<User>"
模型类有错误吗?
【问题讨论】:
-
这些行看起来很可疑:
List<User> decodedJSON = json.decode(listOfUser.body); AllUsers arrayOfAlluser = AllUsers.formJson(decodedJSON);你确定这些表达式的类型是正确的吗?我会同时使用var -
其实我也不是很清楚。我根据我的理解编写了代码,所以使用了你所说的 var 但同样的问题发生了。