KAR Shinyong
KAR Shinyong

Reputation: 41

type 'List<String>' is not a subtype of type 'String' in type cast when http post the list array

I have a selectedItems in the list:

List<String> _selectedItems = [];

Then, I want to pass this _selectedItems like this:

Future<void> _filterItem(List<String> _selectedItems) async {
    ProgressDialog pr = ProgressDialog(context,
        type: ProgressDialogType.Normal, isDismissible: false);
    pr.style(message: "Loading...");
    await pr.show();
    http.post("https://one.com/myapp/php/load_data.php", body: {

      "_selectedItems":_selectedItems,

    }).then((res) {
      if (res.body == "nodata") {
        setState(() {
          print("No Found");
        });
      } else {
        setState(() {
          var extractdata = json.decode(res.body);
          tutordata = extractdata["mydata"];
        });
      }
    }).catchError((err) {
      print(err);
    });
    await pr.hide();
  }

Passing this _selectedItems throws the error type 'List<String>' is not a subtype of type 'String' in type cast What should I do?

Upvotes: 2

Views: 307

Answers (2)

Bach
Bach

Reputation: 3326

When exploring the documentation for http.post(), you can see what types the body can be:

body sets the body of the request. It can be a String, a List or a Map<String, String>

Right now, your code is passing a Map<String, List<String>> to the body, when it needs to be Map<String, String> instead:

http.post("https://one.com/myapp/php/load_data.php", body: {
      "_selectedItems":_selectedItems,
    })

You can do this:

import 'dart:convert';

http.post("https://one.com/myapp/php/load_data.php", body: {
      "_selectedItems": jsonEncode(_selectedItems),
    })

Btw, you can make some improvement on the code. First, for the logic flow, it's often good practice to separate the result of an API call to a setState() since it would be easier to anticipate the flow of the app. You can read more about FutureBuilder and StreamBuilder, as well as BLoC pattern.

For the clean code, you can apply principles from the styling documentation as well. Some adjustment can be made like using CamelCase instead of normal case, so extractData instead of extractdata.

Upvotes: 0

AL.Sharie
AL.Sharie

Reputation: 1615

body: takes <String, String> and you are trying to give it <String, List<String>>

convert your List<String> to JSON string using jsonEncode

Upvotes: 1

Related Questions