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

Last updated on July 17, 2021 A Goodman Loading... Post a comment

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 {
      final String apiEndpoint =
          'https://www.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
0 Comments
Inline Feedbacks
View all comments

You May Also Like