Hi Guys I am getting this error when trying to connect API's in flutter, I followed a tutorial but when trying to connect the newsapi I started getting this error " a value type "post" can't be assigned to a variable of the type 'List?'" Does anyone know how I can fix this?
Here is the services file
import 'package:new_cdsc/Model/post.dart';
import 'package:http/http.dart' as http;
class RemoteService {
Future<Post?> getPosts() async {
var client = http.Client();
var uri = Uri.parse(
'https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=a04fc11949fc4633aa00fb01f37957e7');
var response = await client.get(uri);
if (response.statusCode == 200) {
var json = response.body;
postFromJson(json);
return postFromJson(json);
}
}
}
Here is the section of code where I am getting the error in my mainpage file
class _NewsState extends State<News> {
late Future<Post?> _newsModel;
List<Post>? posts;
var isLoaded = false;
@override
void initState() {
super.initState();
getData();
}
getData() async {
posts = await RemoteService().getPosts();//error here
if (posts != null) {
setState(() {
isLoaded = true;
});
}
}
CodePudding user response:
Since you haven't posted implementation of the postsFromJson(json)
function, I am assuming the error (most likely) lies within. API returns a response of the following structure:
{
"status": "ok",
"totalResults": 70,
"articles": [...]
}
So, make sure that within your postsFromJson(json)
function, you are accessing the articles list properly. There are 2 ways to do this:
- Directly pass the articles list to the
postsFromJson()
function.
if (response.statusCode == 200) {
var json = response.body['articles'];
return postFromJson(json);
}
- Changing the structure of
postsFromJson()
function.
Map<String, dynamic> postsFromJson(Map<String, dynamic> json) {
final totalArticles = json['totalResults'];
final articles = json['articles'];
// Use articles.
}
As a side note, please make sure not to include API keys or other sensitive data with question. In such scenarios, try to post a rough structure of the response you are dealing with.
CodePudding user response:
It looks like RemoteService().getPosts()
returns a list
, but you are assigning this to post
which has a type List<Post>?
. To fix this, cast RemoteService().getPosts()
to a List<Post>?
by calling
posts = await RemoteService().getPosts() as List<Post>;
If you're sure it returns a List
of Post
data types.