错误:List<动态>不是Map< String,dynamic>类型的子类型. [英] Error: List<dynamic> is not a subtype of type Map<String, dynamic>

查看:352
本文介绍了错误:List<动态>不是Map< String,dynamic>类型的子类型.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个通过api读取数据的应用,并且正在尝试从JSON占位符解析JSON api.

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

我为用户创建了一个模型类(users_future_model.dart):

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"]
    );
  }
}

这是将json读取到小部件中的main.dart:

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}");
                  }
                })
          ],
        ),
      )
    );
  }
}

这是我试图读取的JSON信息,尽管它只是其中的一小部分:

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: "Sincere@april.biz",
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"
}
}

我当前遇到的错误是:

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

我该如何纠正此错误?

推荐答案

API返回JSON数组而不是json对象,因此列表不是Map.

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

即用户json是Json Array的第一个元素.

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]);

这篇关于错误:List&lt;动态&gt;不是Map&lt; String,dynamic&gt;类型的子类型.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆