Reputation: 6082
I'm just parsing complex JSON and display on listView for learning purpose.
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),
);
}
}
So, My question is each time i'm getting fail with so many error like.
type 'Future' is not a subtype of type 'Future'
I know there are so many mistake but I'm new to Flutter. Where i'm going wrong? How to solve this issue please guide me on right direction.
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>"
Is there any mistake in model class ?
Upvotes: 0
Views: 2802
Reputation: 63039
Throw away the AllUsers
type, and the arryOfUser
member. You don't need them, and by putting them in, you haven't matched the expectation of FutureBuilder.
class UserViewModel {
Future<List<User>> fetchUserData() async {
var response = await http.get('https://jsonplaceholder.typicode.com/users');
List<User> users = json.decode(response.body).map((u) => User.formJson(u)).toList();
print("users $users");
print("response === >> ${users[0].company.catchPhrase}");
return users;
}
}
class HomeScreenState extends State<HomeSceen> {
UserViewModel userViewmodel;
@override
initState(){
super.initState();
userViewmodel = UserViewModel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("JSON Parsing")
),
body: Container(
child: FutureBuilder<List<User>>(
future: userViewmodel.fetchUserData(),
builder: (context, snap){
return setupListView(snap.data);
},
),
),
);
}
Widget setupListView(List<User> users){
return ListView.builder(
itemCount: users.length,
itemBuilder: (BuildContext context, int index) {
setupListTile(users[index]);
},
);
}
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),
);
}
}
Upvotes: 1