3

Displaying A-List fetched from a 3rd a Third Party API with the search Function the error only shows when I ran the App, It Says _InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable

Please Welp *** Edit A new Error Showed after playing with the code this error showed type 'String' is not a subtype of type Map-dynamic, dynamic-

        Future<Null> getStoreDetails() async {
                var basicAuth = 'Basic ' +
                    base64Encode(utf8.encode('api_token_key'));
                var result;
             
                var response = await http.get(url, headers: {'authorization': basicAuth});
                if (response.statusCode == 200) {
                  var responseJson = json.decode(response.body);
                  setState(() {
             /Where the error is 
                    for (Map storedetails in responseJson) {
                      _searchResult.add(StoreDetails.fromJson(storedetails));
                    }
                  });
                } else if (response.statusCode != 200) {
                  result = "Error getting response:\nHttp status ${response.statusCode}";
                  print(result);
                }
              }
              @override
              void initState() {
                super.initState();
                getStoreDetails();
              }

Data Model Class

class StoreDetails {
  final int businessunitid;
  String citydescription;

  StoreDetails({
    this.businessunitid,
    this.citydescription,
  });

   factory StoreDetails.fromJson(Map<String, dynamic> data) {
    return new StoreDetails(
      businessunitid: data['businessunitid'],
      citydescription: data['citydescription'],
      
    );
  }
}

The Error

E/flutter ( 3566): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'
E/flutter ( 3566): #0      SearchStoreState.getStoreDetails.<anonymous closure> (package:rsc_prototype/screens/searchstore_screen.dart:43:34)
E/flutter ( 3566): #1      State.setState (package:flutter/src/widgets/framework.dart:1125:30)
E/flutter ( 3566): #2      SearchStoreState.getStoreDetails (package:rsc_prototype/screens/searchstore_screen.dart:42:7)
E/flutter ( 3566): <asynchronous suspension>
E/flutter ( 3566): #3      SearchStoreState.initState (package:rsc_prototype/screens/searchstore_screen.dart:56:5)
E/flutter ( 3566): #4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3751:58)
user10040349
  • 283
  • 3
  • 7
  • 16

4 Answers4

7

The value of responseJson is a map. You are trying to do a for ... in on it, and that only works with iterables, and maps are not iterables.

You need to figure out the structure of the JSON you receive. It might contain a list that you want to iterate, or you might want to iterate responseJson.values. It's impossible to know without knowing the format and what you want to do with it.

If, as you say in a comment below, the JSON is a single object, then your code should probably just be:

...
setState(() {
  _searchResult.add(StoreDetails.fromJson(responseJson));
});
...

(I don't know enough about Flutter to know whether it's good practice to have an asynchronous initialization of the state, but I expect it to be dangerous - e.g., the widget might get destroyed before the setState is called).

lrn
  • 64,680
  • 7
  • 105
  • 121
  • { "ID": 0, "BusinessUnitID": 1, "CompanyCode": "Code", "Number": 419, "Name": "Some Name", "ShortName": "ShortName", "City": "City City" }, The JSON format is like this and I only want to retrieve is the city and the businessunitid for the listing and search function – user10040349 Jul 26 '18 at 06:44
  • just learned the different structures of the Json through this article https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51 Thanks for answering <3 – user10040349 Jul 26 '18 at 08:44
  • and the Json I have is not a list of maps – user10040349 Jul 26 '18 at 09:58
0

I you are working with php this is a its working example, remember this 'json_encode($udresponse['userdetails']); return the appropriate array format you need, and before array_push($udresponse['userdetails'],$userdetails); add each item to the array.

$udresponse["userdetails"] = array();
$query = mysqli_query($db->connect(),"SELECT * FROM employee WHERE  Employee_Id ='$UserId'") or die(mysqli_error());
if (mysqli_num_rows($query) > 0) {
    while ($row = mysqli_fetch_array($query)) {
        $userdetails= array();
        // user details
        $userdetails["customerid"]=$row["Employee_Id"];
        $userid=$row["Employee_Id"];
        $userdetails["username"]=$UserName;
        $userdetails["fullname"]=$Fullname;
        $userdetails["email"]=$Email;
        $userdetails["phone"]=$Phone;
        $userdetails["role"]=$UserRole;
        $userdetails["restaurantid"]=$RestaurantId;
        array_push($udresponse['userdetails'],$userdetails);
    }  
    $udresponse["success"] = 1;
    $udresponse["message"] = "sign in Successful";
    //echo json_encode($response);
    echo json_encode($udresponse['userdetails']);
} else {   
    $udresponse["success"] = 2;
    $udresponse["message"] = "error retrieving employee details";
    echo json_encode($udresponse);
}
AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
  • You have an error. [`mysqli_error()`](https://www.php.net/manual/en/mysqli.error.php) needs one argument. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Oct 30 '19 at 22:28
  • That was good programming practice thanks AbdelAziz AbdelLatef. – Abdul razak Nov 28 '19 at 04:07
0

_InternalLinkedHashMap<String, dynamic> is not a subtype of type Iterable<dynamic>

I think that you are trying to set the map data to a list. Map data is coming from the backend and you are trying to set it in a list.

You can simply fix it by returning the array from the backend instead of Map.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
0

I drafted some code which raised this very error, hence how I found this post.

I found the error was caused by treating data from the API with the jsonDecode function too soon.

For example, my draft was final dynamic responseData = jsonDecode(response.body); (but the jsonDecode function was used before any sifting was actually called for or wanted).

To resolve the error, I changed my draft to final dynamic responseData = response.body; (and left the jsonDecode function for later).

The difference is that the jsonDecode function treats the retrieved data, and that must be what led to the error message : )

mathems32
  • 115
  • 9