Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: List<dynamic> is not a subtype of type Map<String, dynamic>

Tags:

json

flutter

I am currently building an app to read data through an api and I am trying to parse a JSON api from JSON Placeholder.

I made a model class for the Users (users_future_model.dart):

class Users {
  final int userID;
  final String name;
  final String username;
  final String email;
  final Address address;

  Users({this.userID, this.name, this.username, this.email, this.address});

  factory Users.fromJson(Map<String, dynamic> usersjson)=> Users(
      userID: usersjson["id"],
      name: usersjson["name"],
      username: usersjson["username"],
      email: usersjson["email"],
      address: Address.fromJson(usersjson["address"])
  );
}

class Address{

  final String street;
  final String suite;
  final String city;
  final String zipcode;

  Address({this.street, this.suite, this.city, this.zipcode});

  factory Address.fromJson(Map<String, dynamic> addjson){

    return Address(
      street: addjson["street"],
      suite:  addjson["suite"],
      city: addjson["city"],
      zipcode: addjson["zipcode"]
    );
  }
}

This is the main.dart to read the json into the widget:

import 'package:flutter/material.dart';
import 'model/users_future_model.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;

final String jsonplaceholder = "http://jsonplaceholder.typicode.com/users/";

//Future method to read the URL
Future<Users> fetchInfo() async{
  final response = await http.get(jsonplaceholder);
  final jsonresponse = json.decode(response.body);

  return Users.fromJson(jsonresponse);
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Parse JSON"),
      ),
      body: new Center(
        child: new Column(
          children: <Widget>[
            new FutureBuilder(
                future: fetchInfo(),
                builder: (context, snapshot){
                  if(snapshot.hasData){
                    return new Text(snapshot.data.email);
                  }else if(snapshot.hasError){
                    return new Text("Error ${snapshot.error}");
                  }
                })
          ],
        ),
      )
    );
  }
}

This is the JSON information i'm trying to read although its only a small part of it:

{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "[email protected]",
address: {
 street: "Kulas Light",
 suite: "Apt. 556",
 city: "Gwenborough",
 zipcode: "92998-3874",
 geo: {
  lat: "-37.3159",
  lng: "81.1496"
 }
},
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
 name: "Romaguera-Crona",
 catchPhrase: "Multi-layered client-server neural-net",
 bs: "harness real-time e-markets"
}
}

The error i am currently running into is:

Error type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

How do i rectify this error?

like image 626
Asyraf Dayan Avatar asked Aug 15 '18 07:08

Asyraf Dayan


4 Answers

API returns JSON array not json object so that is List not Map.

i.e. User json is first element of Json Array.

So to get first element use first index. Inside fetch Info update

return Users.fromJson(jsonresponse[0]);

like image 96
Dhiraj Sharma Avatar answered Oct 25 '22 04:10

Dhiraj Sharma


var streetsFromJson = parsedJson['streets'];
List<String> streetsList = new List<String>.from(streetsFromJson);

Thnx for https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51

like image 22
Muzaffar Abduboqiyev Avatar answered Oct 25 '22 03:10

Muzaffar Abduboqiyev


Check out this Answer

 Future<List<ProductList>> getProductList() async {
  print("comes");
  String productURl= mainURL+'api/store/product-with-category/';

  final response = await http.get(productURl,headers:{"Content-Type": 
 "application/json"});
  List jsonResponse = json.decode(response.body);
  return jsonResponse.map((job) => new ProductList.fromJson(job)).toList();
  
}

Fetch function

    FutureBuilder<List<ProductList>>(
    future: getProductList(),
    builder: (context, snapshot) {
      print("snapshot");
      print(snapshot.data);
      if (snapshot.hasData) {
        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: GridView.builder(
          itemCount: snapshot.data.length,
            gridDelegate:SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2,),
            itemBuilder:  (BuildContext context, int i){
              return Card(
                child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(width: 0.5,color: Colors.grey)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: <Widget>[
                         text18(snapshot.data[i].title, Colors.black, FontWeight.bold)
                      ],
                    ),
                  ),
                ),
              );
            }
        )
        );
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }


      // By default, show a loading spinner.
      return CircularProgressIndicator();
    },
  ),

just change URL and create model class

like image 37
Mr vd Avatar answered Oct 25 '22 04:10

Mr vd


Just pay attention to the error

List<dynamic> is not a subtype of type Map<String, dynamic>

basically it means the data which you are receiving after hitting a webservice is in form of List but inside data class which you have used is of type Map .So, it is unable to parse the data due to structure mismatch as Map is defined in instead of List in data class.

Recheck your Json response and corresponding PODO class

like image 37
master Gaurav Avatar answered Oct 25 '22 04:10

master Gaurav