我正在解码一个响应体,我得到了错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
我在Udemy上学习颤振教程时,正在尝试使用API。教程说要使用https://javiercbk.github.io/json_to_dart/将JSON转换为Dart。我把JSON从https://www.openbrewerydb.org/并将其转换为Dart,但我遇到的问题是,当我尝试解码API时,我得到了未处理的错误异常:“List”类型不是“Map”类型的子类型
作为一个刚刚接触颤振/飞镖的人,我不确定如何解决这样的错误。我的代码贴在下面以供参考。欢迎任何帮助!
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
这里的示例JSON显示了一个示例输出,它将是代码中什么是BreweryModel的List
。因此,您应该尝试生成BreweryModel的List
。当您使用JSON to dart转换器时,您可能没有复制整个示例JSON。以下是一个示例修复程序,用于处理正确接收到的List
,但实际需要的内容可能会因预期应用程序而异。
网络类:
返回BreweryModel
s的列表
:
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');
}
}
您可以在下面复制粘贴运行完整代码
步骤1:使用Future
Future<List<BreweryModel>> breweryObject;
步骤2:使用
未来
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)
,因为它是一个列表
工作演示
完整代码
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,
),
],
),
));
});
}
}
}));
}
}
我对使用颤振和特定于平台的代码非常陌生,所以如果这是一个愚蠢的问题,请原谅我。我正在使用一个事件通道将数据从android端返回到Flatter。我正在返回一份清单 但是,当我试图添加它时,它给出了一个异常,“未处理的异常:类型'列表'不是类型'列表'的子类型 这是我要将贴图对象添加到的列表。 列表 这是我的添加代码。忽略print语句。 我尝试过像cast或from这样的方法,但它对我不起作用,
更新:感谢@Rjulcaa回答我的地图现在是一个列表,但是列表没有显示在用户界面上。我转过来,我需要用FutureBuilder来处理未来,所以如果有人面临这个问题,记得在你的用户界面主体中添加一个FutureBuilder,并在构建器上返回你想要显示的小部件。 我正在制作一个todo列表教程,我正在尝试添加JSON上的编码功能,我的todoList将其保存在SharedReferences上,当
我正在开发我的flutter应用程序的身份验证。请帮我解决这个问题。我无法识别返回这样一个错误的问题,声明未处理异常:类型列表不是类型字符串的子类型。 以下是登录屏幕的代码: 执行登录的上述代码部分: 错误
Family_View.Dart family_provider.dart
我试图从一个API获取数据,但我一直得到上面的错误。下面是我的API响应的结构 下面是我如何获取数据的 知道我做错了什么吗?
我一直在我的颤振应用程序中使用sembast,我在我的类设备中包含我的类温度列表时遇到了问题。我已经包括以下两个类。 我得到未处理的异常:键入“ImmutableMap” 这种方法似乎被用于其他问题的解决方案,这些问题似乎与我的问题几乎相同,所以我不确定这里有什么问题,以及我尝试过的其他解决方案。