Flutter Error: The argument type ‘String’ can’t be assigned to the parameter type ‘Uri’

Updated: August 24, 2023 By: A Goodman 2 comments

If you’re using the http package (version 0.13 or newer), you might run into the following error when sending HTTP requests:

The argument type 'String' can't be assigned to the parameter type 'Uri'

The cause of this error is that the functions provided by the http package previously received arguments with both String and Uri types, but now it only accepts Uri types.

Let’s Fix It

You can fix the mentioned issue with one line of code. By using the Uri.parse() method, you can create a new Uri object by parsing a URI string.

Example:

import 'package:http/http.dart' as http;

/* ... */
void _sendPostRequest() async {
    try {
      const String apiEndpoint =
          'https://api.kindacode.com/this-is-a-fiction-api-endpoint'; 
      // Replace with your own api url

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

      // Do something with the response
      print(response);
    } catch (err) {
      // Handling error
      print(err);
    }
}

Note that the Uri class comes with dart:core so you can use it right away.

Further reading:

You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
Sushil Kumar Pugalia
Sushil Kumar Pugalia
1 year ago

Thanks for this method which is very helpful.

Al Mamun sowrov
Al Mamun sowrov
2 years ago

Thanks this method is helpful. Anybody need apps development hire me [email protected]

Related Articles