http.post problem after Flutter 2 upgrade

Viewed 442

I have just updated to Flutter 2. I updated all the dependencies including http. Now I have a problem with the following:

Future<UserLogin> fetchStaff(String pUserName, String pPassword) async {
  final response = await http
      .post(Uri.encodeFull('$kBaseUrl/LoginService/CheckLogin'),
          headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
          body: '{ "pUser": "$pUserName", "pPassword": "$pPassword"}')
      .timeout(Duration(seconds: kTimeOutDuration));

I'm getting an error on the: Uri.encodeFull('$kBaseUrl/LoginService/CheckLogin'

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

$kBaseUrl = 'https://subdom.mydomain.com:443/mobile';

What do I need to change?

3 Answers

Like the error says, this is because post function expects a Uri and you have passed a String (returned by Uri.encodeFull) to it. You need to use Uri.parse to pass a Uri to it.

final response = await http
      .post(Uri.parse('$kBaseUrl/LoginService/CheckLogin'),

Post method used to take string previously, now they have modified to Uri

so used, Uri.parse to get the uri

.post(Uri.parse(Uri.encodeFull('$kBaseUrl/LoginService/CheckLogin'))

If you had a String, such as:

String strUri="${yourBaseUrl}/yourPath/yourFile";

Using

http.post(Uri.parse(strUri),
  headers: {...},
  body: {...},
);

is enough to get all working back.

You may try Uri.tryParse(strUri) to handle null if the uri string is not valid as a URI or URI reference.

Related