I am getting this error
I cannot seem to get what I am doing wrong please help.
I am fetching the data through a rest api
Here is the code:
FutureBuilder<List<Articles>>(
future: fetchApiData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.separated(
itemBuilder: (context, index) {
Articles articles = snapshot.data![index];
const SizedBox(height: 150,);
return Container(
padding: const EdgeInsets.all(10),
foregroundDecoration: BoxDecoration(
border: Border.all(
color: golden,
width: 2,
),
borderRadius: BorderRadius.circular(5),
),
width: 180,
height: 139,
margin: const EdgeInsets.all(5),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(articles.urlToImage!),
fit: BoxFit.fill,
),
),
);
},
itemCount: snapshot.data!.length, separatorBuilder: (BuildContext context, int index) {
return const SizedBox(height: 10,);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
Future<List> fetchApiData() async {
final response = await http
.get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=dee40e91ae644e9d818dd88498534c71'));
if (response.statusCode == 200) {
List<dynamic> list = convert.jsonDecode(response.body);
List apiData =
list.map((e) => Articles.fromJson(e)).toList();
return apiData;
} else {
throw Exception('Failed to load data');
}
}
I am a beginner in programming and flutter in general
The response of the api is okay I have tested it Used postman to test the result
CodePudding user response:
Because your fetchApiData function return List<dynamic>
type in future, flutter can't know dynamic
type is Articles
type, so change your fetchApiData to this :
Future<List<Articles>> fetchApiData() async {
final response = await http
.get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=dee40e91ae644e9d818dd88498534c71'));
if (response.statusCode == 200) {
List<dynamic> list = convert.jsonDecode(response.body);
List<Articles> apiData =
list.map((e) => Articles.fromJson(e)).toList();
return apiData;
} else {
throw Exception('Failed to load data');
}
}