Home > OS >  In Flutter "final response = await http.get(url);" I am getting an error in the url part o
In Flutter "final response = await http.get(url);" I am getting an error in the url part o

Time:07-30

I am getting an error in the url part of the code, I have shown the error in the screenshot. How can I fix my code without changing its function.

error message

Future<List<Articles>?> getNews() async {

String url = "https://jsonplaceholder.typicode.com/posts";
final response = await http.get(url);

if (response.body.isEmpty) {
  final responseJson = json.decode(response.body);
  News news = News.fromJson(responseJson);
  return news.articles;
}
return null;}

CodePudding user response:

You need to pass Uri instead of string.

 final response = await http.get(Uri.parse(url));

CodePudding user response:

You can assign uri something like this

var uri= Uri.https('jsonplaceholder.typicode.com', 'posts');

And if you want to add queryparametrs then use below code

final queryParameters =
    {
      'key' : 'value',
    };
    var uri= Uri.https('jsonplaceholder.typicode.com', 'posts',queryParameters);

And use this uri in place of Url.

final response = await http.get(uri);
  • Related