import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:trilhaapp/model/post_model.dart';
class PostsRepository {
Future<List<PostModel>> fetchPosts() async {
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
var postList = jsonDecode(response.body);
return (postList as List).map((e) => PostModel.fromJson(e)).toList();
} else {
throw Exception('Failed to load post');
}
}
}
body: ListView.builder(
itemCount: posts.length,
itemBuilder: (_, index) {
var post = posts[index];
When I attempt to populate this list, itemCount is 0, but I really shouldn’t be.
Am I fetching wrong?
2
Answers
Please do refer this for the reference:
In the below code we have handled the two things:
1. Loader for the API call:
This has been handled by using the nullable state at the start named as postList.
And in the build method please do observe that a ternary operator has been used to null check the state variable. Which checks the following:
if the postList is null then CircleProgressIndicator will be shown. if the state is non-nullable then the UI will be started to get drawn.
2. Data addition and UI Decomposition after the api call.
Please do observe the following methods for understanding the API calls:
The main function of data loading and the setState method is handled in the postApiGetMethod. Where the API is called and then the value from the api is decoded and it has been assigned to the state. And then the setState method is called ad the data is successfully loaded to the state.
Use
FutureBuilder
and change your code like this: