Fetching pHp array or map as JSON data in Flutter?

Viewed 3169

I am trying to fetch some data from server using json in my flutter app. This is the function I am using.

List<String> userFriendList = ["No Friends"];  

Future<http.Response> _fetchSampleData() {
            return http.get('//link/to/server/fetcher/test_fetcher.php');
}

Future<void> getDataFromServer() async {
            final response = await _fetchSampleData();

            if (response.statusCode == 200) {
              Map<String, dynamic> data = json.decode(response.body);    
                userLvl = data["lvl"].toString();
                userName = data["name"];
                userFriendList = List();
                userFriendList = data["friendlist"];  
            } else {
              // If the server did not return a 200 OK response,
              // then throw an exception.
              print('Failed to load data from server');
            }
}

I get the usrLvl and userName right. But for userFriendList, I get the following error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'

Code on the server end (test_fetcher.php) :

<?php
    $myObj->name = "JohnDoe";
    $myObj->lvl = 24;

    $friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes");

    $myObj->friendlist = $friends;

    header('Content-Type: application/json');
    $myJSON = json_encode($myObj);
    echo $myJSON;
?>
3 Answers

This is a cast error: List<dynamic> != List<String>

You can convert / cast your list in several ways.

I advise you to use this library to simplify your json / Dart object conversion : https://pub.dev/packages/json_serializable

json_serializable will generate the conversion methods (fromJson and toJson) and take care of everything.

It's easier and safer than doing it manually.

Just what the error says. The userFriendList is of type List you have it as List.

List<String> userFriendList = ["No Friends"]; 

Should be

List<dynamic> userFriendList = []; 

Or a different list entirely if this doesn't work for you.

The error explains it. The fetched data from the server api is decoded to type List<dynamic> and you declared userFriendList to be of type List<String>. What you need to do is change the type of userFriendList from

List<String> userFriendList = ["No Friends"]; 

to:

List<dynamic> userFriendList = [];  
Related