Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list from JSON in Flutter

Following an online example I have the following code:

_fetchData() async {
    setState(() {
      isLoading = true;
    });

    final response = await http.get(
        "https://apiurl...");

    if (response.statusCode == 200) {
      print(json.decode(response.body).runtimeType); // _InternalLinkedHashMap<String, dynamic>

      list = (json.decode(response.body) as List)
          .map((data) => Model.fromJson(data))
          .toList();

      setState(() {
        isLoading = false;
      });
    } else {
      throw Exception('Failed to load');
    }
  }

Which returns this error:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

This is the response from the API:

{"results":[{"docid":"123434","title":"A title"}, ...]}

Model:

class Model {
  final String title;
  final String docid;

  Model._({this.title, this.docid});

  factory Model.fromJson(Map<String, dynamic> json) {
    return new Model._(
      title: json['title'],
      docid: json['docid'],
    );
  }
}

I understand that the above factory is expecting the argument to be Map<String, dynamic> and the format of the json is different and can be changed, but want to know how to make it work with this format.

*** Edit

Working ListView

body: Column(
    children: <Widget>[
      Padding(
        padding: EdgeInsets.all(10.0),
        child: TextField(
          onChanged: (value) {
            ...
          },
          controller: _searchController,
          decoration: InputDecoration(

          ...
          ),
        ),
      ),
      Expanded(
        child: SizedBox(
          height: 200.0,
          child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                return Text(list[index].title);
              }),
        ),
      )
    ],
  ),
like image 547
Ciprian Avatar asked May 08 '19 23:05

Ciprian


3 Answers

The reason that print(json.decode(response.body).runtimeType) prints _InternalLinkedHashMap is because the top level of your json is indeed a map; {"results":[ opens with a brace.

So, json.decode(response.body) isn't a list and cannot be cast to one. On the other hand, json.decode(response.body)['results'] is a list.

You need:

  list = json.decode(response.body)['results']
      .map((data) => Model.fromJson(data))
      .toList();
like image 134
Richard Heap Avatar answered Oct 18 '22 21:10

Richard Heap


i tried like this and this worked

List<UserModel> users = (json.decode(response.body) as List)
      .map((data) => UserModel.fromJson(data))
      .toList();

My Json response is like :-

[{"id":4,"name":"1","email":"admin","password":"dc4b79a9200aa4630fee652bb5d7f232c503b77fb3b66df99b21ec3ff105f623","user_type":"1","created_on":"2020-01-13 12:50:28","updated_on":"2020-01-14 11:42:05","flags":"00000"},{"id":31,"name":"avi","email":"[email protected]","password":"dc4b79a9200aa4630fee652bb5d7f232c503b77fb3b66df99b21ec3ff105f623","user_type":"1","created_on":"2020-03-15 11:39:16","updated_on":"2020-03-15 11:39:16","flags":null}]
like image 13
avinash Avatar answered Oct 18 '22 20:10

avinash


The following was working for me:

List<Model>.from(
  json.decode(response.body)
  .map((data) => Model.fromJson(data))
)
like image 3
Ruthinke Avatar answered Oct 18 '22 21:10

Ruthinke