Serdar Bilgili
Serdar Bilgili

Reputation: 1

In Flutter "final response = await http.get(url);" I am getting an error in the url part of the code

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;}

Upvotes: 0

Views: 3079

Answers (3)

Crescent Sambila
Crescent Sambila

Reputation: 11

You have to remove that http. before get() and pass Uri like this:

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

Upvotes: 0

Rohan Jariwala
Rohan Jariwala

Reputation: 2048

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);

Upvotes: 1

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63829

You need to pass Uri instead of string.

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

Upvotes: 2

Related Questions