void main() => runApp( MaterialApp(
home: HomePage(),
));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController controller = TextEditingController();
// Get json result and convert it to model. Then add
Future<Null> getUserDetails() async {
final response = await http.get(Uri.parse(url));
final responseJson = json.decode(response.body);
setState(() {
for (Map user in responseJson) {
Map<String, dynamic> _userDetails =
user.map((key, value) => MapEntry(key, value?.toString()));
_userDetails.addAll(_userDetails);
print("fdsfsd: ");
print(_userDetails.length);
}
});
}
@override
void initState() {
super.initState();
getUserDetails();
}
Till this point things do work fine. The print statement shows the good length of the list.
When this needs to go in the GUI through build, there suddenly the list becomes empty:
This print statement results 0. I have removed the extra code for clarity sake.
@override
Widget build(BuildContext context) {
print("FFFF: ");
print(_userDetails.length);
return Scaffold(
appBar: AppBar(
title: Text('Home'),
elevation: 0.0,
),
body: Column(
children: <Widget>[
Container(
..........
}
Rest of the code is here:
List<UserDetails> _searchResult = [];
List<UserDetails> _userDetails = [];
final String url = 'https://jsonplaceholder.typicode.com/users';
class UserDetails {
final int? id;
final String? firstName, lastName, profileUrl;
UserDetails(
{this.id,
this.firstName,
this.lastName,
this.profileUrl =
'https://i.amz.mshcdn.com/3NbrfEiECotKyhcUhgPJHbrL7zM=/950x534/filters:quality(90)/2014%2F06%2F02%2Fc0%2Fzuckheadsho.a33d0.jpg'});
factory UserDetails.fromJson(Map<String, dynamic> json) {
return UserDetails(
id: json['id'],
firstName: json['name'],
lastName: json['username'],
);
}
}