我只是解析复杂的JSON并在listView上显示以用于学习目的 .
API:https://jsonplaceholder.typicode.com/users
1) Model Class
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) View Portion of the code.
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),
);
}
}
所以,我的问题是,每当我因为如此多的错误而失败时 .
类型'Future'不是'Future'类型的子类型
我知道有很多错误,但我是Flutter的新手 . 哪里出错了?如何解决这个问题请指导我正确的方向 .
UPDATED
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>"
模型类有什么错误吗?
1 回答
扔掉
AllUsers
类型和arryOfUser
成员 . 你没有满足FutureBuilder的期望 .