未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic

Posted

技术标签:

【中文标题】未处理的异常:类型 \'List<dynamic>\' 不是类型 \'Map<String, dynamic【英文标题】:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic 【发布时间】:2020-11-05 13:15:32 【问题描述】:

我正在解码响应正文并收到错误消息:

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

我正在尝试使用 API,同时遵循 Udemy 上的颤振教程。该教程说使用 https://javiercbk.github.io/json_to_dart/ 将 JSON 转换为 Dart。我从https://www.openbrewerydb.org/ 获取 JSON 并将其转换为 Dart,但我遇到的问题是当我尝试解码 API 时出现错误 Unhandled Exception: type 'List' is not a subtype of type 'Map

作为 Flutter/Dart 的新手,我不确定如何解决此类错误。我的代码发布在下面以供参考。欢迎任何帮助!

BreweryModel.dart

class BreweryModel 
  int id;
  String name;
  String breweryType;
  String street;
  String city;
  String state;
  String postalCode;
  String country;
  String longitude;
  String latitude;
  String phone;
  String websiteUrl;
  String updatedAt;

  BreweryModel(
      this.id,
      this.name,
      this.breweryType,
      this.street,
      this.city,
      this.state,
      this.postalCode,
      this.country,
      this.longitude,
      this.latitude,
      this.phone,
      this.websiteUrl,
      this.updatedAt);

  factory BreweryModel.fromJson(Map<String, dynamic> json) 
    return BreweryModel(
        id: json['id'],
        name: json['name'],
        breweryType: json['brewery_type'],
        street: json['street'],
        city: json['city'],
        state: json['state'],
        postalCode: json['postal_code'],
        country: json['country'],
        phone: json['phone']);
  

  Map<String, dynamic> toJson() 
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['brewery_type'] = this.breweryType;
    data['street'] = this.street;
    data['city'] = this.city;
    data['state'] = this.state;
    data['postal_code'] = this.postalCode;
    data['country'] = this.country;
    data['longitude'] = this.longitude;
    data['latitude'] = this.latitude;
    data['phone'] = this.phone;
    data['website_url'] = this.websiteUrl;
    data['updated_at'] = this.updatedAt;
    return data;
  

Network.dart

import 'package:brewery_app/model/BreweryModel.dart';
import 'package:http/http.dart';
import 'dart:convert';

class Network 
  Future<BreweryModel> getBreweryModel(String cityName) async 
    var URL = 'https://api.openbrewerydb.org/breweries?by_city=$cityName';

    final response = await get(Uri.encodeFull(URL));

    print('URL $Uri.encodeFull(URL)');

    if (response.statusCode == 200) 
      print(response.body);
      return BreweryModel.fromJson(json.decode(response.body));
     else 
      throw Exception('Error getting brewery');
    
  

Main.dart

import 'package:brewery_app/model/BreweryModel.dart';
import 'package:brewery_app/network/network.dart';
import 'package:flutter/material.dart';

void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Brewery(),
    );
  


class Brewery extends StatefulWidget 
  @override
  _BreweryState createState() => _BreweryState();


class _BreweryState extends State<Brewery> 
  Future<BreweryModel> breweryObject;
  String cityName = 'Austin';
  @override
  void initState() 
    // TODO: implement initState
    super.initState();
    breweryObject = Network().getBreweryModel(cityName: cityName);

    breweryObject.then((brewery) 
      print(brewery.city);
    );
  

  @override
  Widget build(BuildContext context) 
    return Container();
  

这是发布到控制台的所有内容

I/flutter (25205): URL https://api.openbrewerydb.org/breweries?by_city=Austin
I/flutter (25205): ["id":6780,"name":"Jester King Brewery","brewery_type":"micro","street":"13187 Fitzhugh Rd","city":"Austin","state":"Texas","postal_code":"78736-6510","country":"United States","longitude":"-98.0824692","latitude":"30.2547264","phone":"5125375100","website_url":"http://www.jesterkingbrewery.com","updated_at":"2018-08-24T16:21:26.875Z","tag_list":[],"id":6822,"name":"Oasis Texas Brewing Company","brewery_type":"micro","street":"6548 Comanche Trl Ste 301","city":"Austin","state":"Texas","postal_code":"78732-1210","country":"United States","longitude":"-98.151206","latitude":"30.043267","phone":"5122849407","website_url":"http://www.otxbc.com","updated_at":"2018-08-24T16:22:10.184Z","tag_list":[],"id":6631,"name":"Barking Armadillo Brewing","brewery_type":"planning","street":"","city":"Austin","state":"Texas","postal_code":"78723-3342","country":"United States","longitude":null,"latitude":null,"phone":"","website_url":"","updated_at":"2018-08-11T21:39:46.076Z","tag_list":[],"id":6632,"name":"Barrel Assem
E/flutter (25205): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
E/flutter (25205): #0      Network.getBreweryModel (package:brewery_app/network/network.dart:15:41)
E/flutter (25205): <asynchronous suspension>
E/flutter (25205): #1      _BreweryState.initState (package:brewery_app/main.dart:31:31)
E/flutter (25205): #2      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4640:58)
E/flutter (25205): #3      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter (25205): #4      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #5      Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #6      SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter (25205): #7      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #8      Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #9      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter (25205): #10     Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter (25205): #11     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter (25205): #12     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter (25205): #13     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #14     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #15     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter (25205): #16     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #17     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #18     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter (25205): #19     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #20     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #21     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter (25205): #22     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
E/flutter (25205): #23     Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter (25205): #24     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter (25205): #25     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)
E/flutter (25205): #26     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter (25205): #27     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #28     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #29     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter (25205): #30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #31     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #32     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5830:14)
E/flutter (25205): #33     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #34     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #35     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter (25205): #36     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
E/flutter (25205): #37     Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter (25205): #38     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
E/flutter (25205): #39     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)
E/flutter (25205): #40     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
E/flutter (25205): #41     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
E/flutter (25205): #42     Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
E/flutter (25205): #43     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
E/flutter (25205): #44     Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
E/flutter (25205): #45     ComponentElement._firstBuild (package:flutter

【问题讨论】:

你能澄清你的错误吗?您的标题表明与正文所说的不同。也请直接复制粘贴出错。 我编辑了帖子,希望能澄清我遇到的错误。 【参考方案1】:

您可以在下面复制粘贴运行完整代码 第 1 步:将Future&lt;List&lt;BreweryModel&gt;&gt; 用于breweryObject;

Future<List<BreweryModel>> breweryObject;     

第 2 步:将Future&lt;List&lt;BreweryModel&gt;&gt; 用于getBreweryModel

Future<List<BreweryModel>> getBreweryModel(String cityName) async 
    var URL = 'https://api.openbrewerydb.org/breweries?by_city=$cityName';

    final response = await http.get(Uri.encodeFull(URL));

    print('URL $Uri.encodeFull(URL)');

    if (response.statusCode == 200) 
      print(response.body);
      return breweryModelFromJson(response.body);

第 3 步:在 getBreweryModel() 中,您需要返回 breweryModelFromJson(response.body),因为它是 List&lt;BreweryModel&gt;

工作演示

完整代码

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

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

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

class BreweryModel 
  int id;
  String name;
  String breweryType;
  String street;
  String city;
  String state;
  String postalCode;
  String country;
  String longitude;
  String latitude;
  String phone;
  String websiteUrl;
  String updatedAt;

  BreweryModel(
      this.id,
      this.name,
      this.breweryType,
      this.street,
      this.city,
      this.state,
      this.postalCode,
      this.country,
      this.longitude,
      this.latitude,
      this.phone,
      this.websiteUrl,
      this.updatedAt);

  factory BreweryModel.fromJson(Map<String, dynamic> json) 
    return BreweryModel(
        id: json['id'],
        name: json['name'],
        breweryType: json['brewery_type'],
        street: json['street'],
        city: json['city'],
        state: json['state'],
        postalCode: json['postal_code'],
        country: json['country'],
        phone: json['phone']);
  

  Map<String, dynamic> toJson() 
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['brewery_type'] = this.breweryType;
    data['street'] = this.street;
    data['city'] = this.city;
    data['state'] = this.state;
    data['postal_code'] = this.postalCode;
    data['country'] = this.country;
    data['longitude'] = this.longitude;
    data['latitude'] = this.latitude;
    data['phone'] = this.phone;
    data['website_url'] = this.websiteUrl;
    data['updated_at'] = this.updatedAt;
    return data;
  


void main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Brewery(title: 'Flutter Demo Home Page'),
    );
  


class Network 
  Future<List<BreweryModel>> getBreweryModel(String cityName) async 
    var URL = 'https://api.openbrewerydb.org/breweries?by_city=$cityName';

    final response = await http.get(Uri.encodeFull(URL));

    print('URL $Uri.encodeFull(URL)');

    if (response.statusCode == 200) 
      print(response.body);
      return breweryModelFromJson(response.body);
     else 
      throw Exception('Error getting brewery');
    
  


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

  final String title;

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


class _BreweryState extends State<Brewery> 
  Future<List<BreweryModel>> breweryObject;
  String cityName = 'Austin';

  @override
  void initState() 
    super.initState();
    breweryObject = Network().getBreweryModel(cityName: cityName);
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text("Demo"),
        ),
        body: FutureBuilder(
            future: breweryObject,
            builder: (context, AsyncSnapshot<List<BreweryModel>> snapshot) 
              switch (snapshot.connectionState) 
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) 
                    return Text(
                      '$snapshot.error',
                      style: TextStyle(color: Colors.red),
                    );
                   else 
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) 
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      snapshot.data[index].name,
                                    ),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].street,
                                    ),
                                  ],
                                ),
                              ));
                        );
                  
              
            ));
  

【讨论】:

【参考方案2】:

示例 JSON here 显示了一个示例输出,它将是您代码中 BreweryModels 的 List。因此,您应该尝试生成ListBreweryModels。当您使用 JSON 到 dart 转换器时,您可能没有复制整个示例 JSON。以下是处理正确接收的List 的示例修复,但您实际需要的内容可能会因您的预期应用程序而异。

网络类:

返回ListBreweryModels:

Future<List<BreweryModel>> getBreweryModel(String cityName) async 
    var URL = 'https://api.openbrewerydb.org/breweries?by_city=$cityName';

    final response = await get(Uri.encodeFull(URL));

    print('URL $Uri.encodeFull(URL)');

    if (response.statusCode == 200) 
      print(response.body);
      List<BreweryModel> toReturn = List()
      List json = json.decode(response.body);
     
      for(Map unparsed in json) 
        toReturn.add(BreweryModel.fromJson(unparsed);
      

      return toReturn;
     else 
      throw Exception('Error getting brewery');
    
  

或者如果您只希望收到的 JSON 中有一个啤酒厂:

Future<BreweryModel> getBreweryModel(String cityName) async 
    var URL = 'https://api.openbrewerydb.org/breweries?by_city=$cityName';

    final response = await get(Uri.encodeFull(URL));

    print('URL $Uri.encodeFull(URL)');

    if (response.statusCode == 200) 
      print(response.body);
      return BreweryModel.fromJson(json.decode(response.body)[0]);
     else 
      throw Exception('Error getting brewery');
    
  

【讨论】:

以上是关于未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic的主要内容,如果未能解决你的问题,请参考以下文章

未处理的异常:类型“List<dynamic>”不是“List<CustomerTransactionDetail>”类型的子类型

未处理的异常:类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型

未处理的异常:类型'List<dynamic>'不是'String'类型的子类型无法获取json数据[重复]

未处理的异常:类型 'List<dynamic>' 不是颤振中类型 'Map<dynamic, dynamic>' 的子类型

未处理的异常:类型“List<dynamic>”不是“List<Map<String, double>>”类型的子类型

未处理的异常:类型“int”不是类型转换中“List<int>”类型的子类型