Flutter 在 ListView 返回类型 String 中显示嵌套 json 不是类型转换中类型“Map<String, dynamic>”的子类型

Posted

技术标签:

【中文标题】Flutter 在 ListView 返回类型 String 中显示嵌套 json 不是类型转换中类型“Map<String, dynamic>”的子类型【英文标题】:Flutter display nested json in ListView return type String is not a subtype of type 'Map<String, dynamic>' in type cast 【发布时间】:2021-05-01 06:27:00 【问题描述】:

我将继续我的 Flutter 之旅。我能够在 ListView 中显示一个简单的 json。 现在我正在尝试使用带有嵌套对象的 json,但每次运行应用程序时都会出现错误

我正在为 Flutter 官方文档中建议的 json 模型类生成代码。

我在解析用户时似乎发生了错误。在调试时,我看到 name 和 surname 解析成功,但是当我跳转到 user.g.dart 中的 details 对象时:

json['details'] == null
        ? null
        : Details.fromJson(json['details'] as Map<String, dynamic>),

我看到了错误:

type String is not a subtype of type 'Map<String, dynamic>' in type cast

如何解决此错误,以及如何访问所有嵌套对象以显示它们?

这是我必须解析的 json。我编辑了,没有arename字段:

数据.json

[
    
        "name": "jhon",
        "surname": "walker",
        "details": "\"work\":\"salary\":\"116\",\"company\":\"evolution\",\"address\":\"street\":\"grand station\",\"city\":\"salt lake\""    
    ,
    
        "name": "peter",
        "surname": "parker",
        "details": "\"work\":\"salary\":\"116\",\"company\":\"evolution\",\"address\":\"street\":\"grand station\",\"city\":\"salt lake\""    
    
]

这是我的模型类:

user.dart

import 'package:json_annotation/json_annotation.dart';
import 'details.dart';

part 'user.g.dart';

@JsonSerializable(explicitToJson: true)
class User 
  User(this.name, this.surname, this.details);

  String name;
  String surname;
  Details details;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);

user.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) 
  return User(
    json['name'] as String,
    json['surname'] as String,
    json['details'] == null
        ? null
        : Details.fromJson(json['details'] as Map<String, dynamic>),
  );


Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>
      'name': instance.name,
      'surname': instance.surname,
      'details': instance.details?.toJson(),
    ;

details.dart

import 'package:json_annotation/json_annotation.dart';
import 'address.dart';
import 'work.dart';
part 'details.g.dart';

@JsonSerializable(explicitToJson: true)
class Details 
  Details(this.work, this.address);

  Work work;
  Address address;

  factory Details.fromJson(Map<String, dynamic> json) =>
      _$DetailsFromJson(json);
  Map<String, dynamic> toJson() => _$DetailsToJson(this);

details.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'details.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Details _$DetailsFromJson(Map<String, dynamic> json) 
  return Details(
    json['work'] == null
        ? null
        : Work.fromJson(json['work'] as Map<String, dynamic>),
    json['address'] == null
        ? null
        : Address.fromJson(json['address'] as Map<String, dynamic>),
  );


Map<String, dynamic> _$DetailsToJson(Details instance) => <String, dynamic>
      'work': instance.work?.toJson(),
      'address': instance.address?.toJson(),
    ;

work.dart

import 'package:json_annotation/json_annotation.dart';
part 'work.g.dart';

@JsonSerializable(explicitToJson: true)
class Work 
  Work(this.salary, this.company);

  String salary;
  String company;

  factory Work.fromJson(Map<String, dynamic> json) => _$WorkFromJson(json);
  Map<String, dynamic> toJson() => _$WorkToJson(this);

work.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'work.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Work _$WorkFromJson(Map<String, dynamic> json) 
  return Work(
    json['salary'] as String,
    json['company'] as String,
  );


Map<String, dynamic> _$WorkToJson(Work instance) => <String, dynamic>
      'salary': instance.salary,
      'company': instance.company,
    ;

地址.dart

import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';

@JsonSerializable(explicitToJson: true)
class Address 
  Address(this.street, this.city);
  
  String street;
  String city;

  factory Address.fromJson(Map<String, dynamic> json) =>
      _$AddressFromJson(json);
  Map<String, dynamic> toJson() => _$AddressToJson(this);

地址.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'address.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Address _$AddressFromJson(Map<String, dynamic> json) 
  return Address(
    json['street'] as String,
    json['city'] as String,
  );


Map<String, dynamic> _$AddressToJson(Address instance) => <String, dynamic>
      'street': instance.street,
      'city': instance.city,
    ;

最后,这是应用程序: main.dart

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'user.dart';
import 'details.dart';
import 'address.dart';
import 'work.dart';
import 'package:built_value/serializer.dart';
import 'dart:convert' as json;
import 'package:meta/meta.dart';
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'dart:developer';

void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;


  Future<List<User>> getUsers() async 
    var url = "empty for now"; // here there will be the request now I' m using fake data
    //final response = await http.get(url);
    //final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
    String data = r'''[
      
        "name": "260",
        "surname": "430011",
        "areaName": "Camera1-Zone1",
        "details": "\"work\":\"salary\":\"116\",\"company\":\"evolution\",\"address\":\"street\":\"grand station\",\"city\":\"salt lake\""
      ,
      
        "name": "260",
        "surname": "430011",
        "areaName": "Camera1-Zone1",
        "details": "\"work\":\"salary\":\"116\",\"company\":\"evolution\",\"address\":\"street\":\"grand station\",\"city\":\"salt lake\""
      
    ]''';
    final parsed = json.jsonDecode(data).cast<Map<String, dynamic>>();
    return parsed.map<User>((json) 
      return User.fromJson(json);
    ).toList();
  

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("List"),
          backgroundColor: Colors.blue,
        ),
        body: Container(
          child: FutureBuilder<List<User>>(
            future: getUsers(),
            builder: (context, snapshot) 
              if (snapshot.hasData) 
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, int index) 
                    return ListTile(
                        title: Text(snapshot.data[index].name),
                        subtitle: Text(snapshot.data[index].surname));
                  ,
                );
               else if (snapshot.hasError) 
                return Center(
                  child: Text(snapshot.error.toString()),
                );
              
              return Center(
                child: CircularProgressIndicator(),
              );
            ,
          ),
        ),
      ),
    );
  

您能帮我解决这个错误并显示所有嵌套数据吗?谢谢!

感谢您的帮助!

【问题讨论】:

这能回答你的问题吗? Error: List<dynamic> is not a subtype of type Map<String, dynamic> 不,我的意思是如果我尝试像在答案中那样返回,我会得到一个空名称引用或类似的东西。我应该循环解析变量并通过使用 [] 运算符访问它们来添加 json 的每个元素?你能给我一个提示吗?谢谢! 【参考方案1】:

我找到了解决办法。

我使用的模型是:

model.dart

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User 
  User(
    this.name,
    this.surname,
    this.areaName,
    this.details,
  );

  String name;
  String surname;
  String areaName;
  String details;

  factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"],
        surname: json["surname"],
        areaName: json["areaName"],
        details: json["details"],
      );

  Map<String, dynamic> toJson() => 
        "name": name,
        "surname": surname,
        "areaName": areaName,
        "details": details,
      ;


Details DetailsFromJson(String str) => Details.fromJson(json.decode(str));

String DetailsToJson(Details data) => json.encode(data.toJson());

class Details 
  Details(
    this.work,
    this.address,
  );

  Work work;
  Address address;

  factory Details.fromJson(Map<String, dynamic> json) => Details(
        work: Work.fromJson(json["work"]),
        address: Address.fromJson(json["address"]),
      );

  Map<String, dynamic> toJson() => 
        "work": work.toJson(),
        "address": address.toJson(),
      ;


class Address 
  Address(
    this.street,
    this.city,
  );

  String street;
  String city;

  factory Address.fromJson(Map<String, dynamic> json) => Address(
        street: json["street"],
        city: json["city"],
      );

  Map<String, dynamic> toJson() => 
        "street": street,
        "city": city,
      ;


class Work 
  Work(
    this.salary,
    this.company,
  );

  String salary;
  String company;

  factory Work.fromJson(Map<String, dynamic> json) => Work(
        salary: json["salary"],
        company: json["company"],
      );

  Map<String, dynamic> toJson() => 
        "salary": salary,
        "company": company,
      ;

主要代码是: main.dart

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'user.dart';
import 'details.dart';
import 'address.dart';
import 'work.dart';
import 'package:built_value/serializer.dart';
import 'dart:convert' as json;
import 'package:meta/meta.dart';
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'dart:developer';

void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class MyHomePage extends StatefulWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  int _counter = 0;


  Future<List<User>> getUsers() async 
    var url = "empty for now"; // here there will be the request now I' m using fake data
    //final response = await http.get(url);
    //final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
    String data = r'''[
      
        "name": "260",
        "surname": "430011",
        "areaName": "Camera1-Zone1",
        "details": "\"work\":\"salary\":\"116\",\"company\":\"evolution\",\"address\":\"street\":\"grand station\",\"city\":\"salt lake\""
      ,
      
        "name": "260",
        "surname": "430011",
        "areaName": "Camera1-Zone1",
        "details": "\"work\":\"salary\":\"116\",\"company\":\"evolution\",\"address\":\"street\":\"grand station\",\"city\":\"salt lake\""
      
    ]''';
    List<User> users= userFromJson(res);
    return users;
  

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("List"),
          backgroundColor: Colors.blue,
        ),
        body: Container(
          child: FutureBuilder<List<User>>(
            future: getUsers(),
            builder: (context, snapshot) 
              if (snapshot.hasData) 
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, int index) 
                    return ListTile(
                        title: Text(snapshot.data[index].name),
                        subtitle: Text(snapshot.data[index].surname));
                  ,
                );
               else if (snapshot.hasError) 
                return Center(
                  child: Text(snapshot.error.toString()),
                );
              
              return Center(
                child: CircularProgressIndicator(),
              );
            ,
          ),
        ),
      ),
    );
  

【讨论】:

【参考方案2】:
 Future<List<User>> getUsers() async 
    var url = "empty for now"; 
   final response = await http.get(url);

     if (response.isEmpty) return null;


    Map<String, dynamic> data = json.decode(response);

    List<dynamic> list = data['data'];

     List<User> result =
     list.map((f) => User.fromJson(f)).toList();

    return result;
  

如果json datan是这样的-->

   
    "name": "260",
    "surname": "430011",
    "areaName": "Camera1-Zone1",
    "details": "work":"salary":"116","company":"evolution","address": 
      "street":"grand station","city":"salt lake"
  ,

你的模型会是这样的:

 import 'dart:convert';
  User userFromJson(String str) => User.fromJson(json.decode(str));

  String userToJson(User data) => json.encode(data.toJson());

 class User 
  User(
    this.name,
    this.surname,
    this.areaName,
    this.details,
 );

String name;
String surname;
String areaName;
Details details;

 factory User.fromJson(Map<String, dynamic> json) => User(
    name: json["name"],
    surname: json["surname"],
    areaName: json["areaName"],
    details: Details.fromJson(json["details"]),
 );

 Map<String, dynamic> toJson() => 
    "name": name,
    "surname": surname,
    "areaName": areaName,
    "details": details.toJson(),
 ;


class Details 
 Details(
    this.work,
    this.address,
 );

 Work work;
 Address address;

  factory Details.fromJson(Map<String, dynamic> json) => Details(
     work: Work.fromJson(json["work"]),
    address: Address.fromJson(json["address"]),
  );

  Map<String, dynamic> toJson() => 
    "work": work.toJson(),
    "address": address.toJson(),
   ;
  

  class Address 
  Address(
    this.street,
    this.city,
  );

String street;
String city;

factory Address.fromJson(Map<String, dynamic> json) => Address(
    street: json["street"],
    city: json["city"],
);

Map<String, dynamic> toJson() => 
    "street": street,
    "city": city,
  ;
 

class Work 
Work(
    this.salary,
     this.company,
);

String salary;
String company;

 factory Work.fromJson(Map<String, dynamic> json) => Work(
    salary: json["salary"],
    company: json["company"],
 );

  Map<String, dynamic> toJson() => 
    "salary": salary,
     "company": company,
   ;
  

或者如果这样:

   
    "name": "260",
    "surname": "430011",
    "areaName": "Camera1-Zone1",
    "details": "\"work\": 
  \"salary\":\"116\",\"company\":\"evolution\",\"address\": 
   \"street\":\"grand station\",\"city\":\"salt lake\""
   

你的模型会是这样的:

import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));

String userToJson(User data) => json.encode(data.toJson());

class User 
 User(
    this.name,
    this.surname,
    this.areaName,
    this.details,
);

String name;
String surname;
String areaName;
String details;

factory User.fromJson(Map<String, dynamic> json) => User(
    name: json["name"],
    surname: json["surname"],
    areaName: json["areaName"],
    details: json["details"],
);

Map<String, dynamic> toJson() => 
    "name": name,
    "surname": surname,
    "areaName": areaName,
    "details": details,
 ;

【讨论】:

我有几句话要说: - 我无法使用 android Studio 找到 response.isEmpty - 我无法使用 Android Studio 找到 json.decode,我只有 jsonDecode 还是需要一个不同的库? - 对于带有所有转义包的 json,我将无法访问单个字段,对吗? 我已经构建了使用带有转义字符的 json 的解决方案,例如您发布的第二个 json。我希望能够使用分离的对象获取所有不同字段的详细信息,就像它应该的那样,而不是只有一个大的 String 对象,并且可能使用正则表达式来获取详细信息中的字段。这可能吗?

以上是关于Flutter 在 ListView 返回类型 String 中显示嵌套 json 不是类型转换中类型“Map<String, dynamic>”的子类型的主要内容,如果未能解决你的问题,请参考以下文章

Flutter项目中ListView的滚动不流畅

Flutter 动画列表:有条件地添加 ListView 项

在 Flutter Listview 中选择卡片

Flutter:如何在 Listview 中删除行之间的空间

在 Flutter 中使用 InheritedWidget 时 ListView 失去滚动位置

我想在 Flutter App 的 Listview 中显示我的 Json 数据