Flutter 错误:期望一个类型为“Map<String, dynamic>”的值,但出现了一个类型为“List<dynamic>”的值
Posted
技术标签:
【中文标题】Flutter 错误:期望一个类型为“Map<String, dynamic>”的值,但出现了一个类型为“List<dynamic>”的值【英文标题】:Flutter Error: Expected a value of type ‘Map<String, dynamic>', but got one of type ‘List<dynamic>' occured 【发布时间】:2021-07-29 02:44:05 【问题描述】:我正在使用http:^0.13.3,
这是我的简单代码,当我运行此代码时出现错误:“预期类型为 'Map
class SubCategoryObject
final int id;
final String category;
SubCategoryObject(@required this.id, @required this.category);
factory SubCategoryObject.fromJson(Map<String, dynamic> json)
return SubCategoryObject(
id: json['id'],
category: json['title'],
);
class SubCategoryListScreen extends StatelessWidget
static const route = 'sub-category-list';
SubCategoryListScreen(Key key) : super(key: key);
Future<SubCategoryObject> getData() async
final res =
await http.get(Uri.https("jsonplaceholder.typicode.com", "todos"));
if (res.statusCode == 200)
return SubCategoryObject.fromJson(jsonDecode(res.body));
else
// If that call was not successful, throw an error.
throw Exception('Failed to load ');
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text("martman"),
),
body: FutureBuilder<SubCategoryObject>(
future: getData(),
builder: (ctx, snapshot)
// Checking if future is resolved or not
if (snapshot.connectionState == ConnectionState.done)
// If we got an error
if (snapshot.hasError)
return Center(
child: Text(
'$snapshot.error occured',
style: TextStyle(fontSize: 18),
),
);
// if we got our data
else if (snapshot.hasData)
return Text(snapshot.data.category);
// Displaying LoadingSpinner to indicate waiting state
return Center(
child: CircularProgressIndicator(),
);
,
),
);
【问题讨论】:
打印并分享您从 api 获取的数据的屏幕截图。我相信这是一个列表而不是地图。 【参考方案1】:请检查以下链接。它返回列表,而不是地图数据。 https://jsonplaceholder.typicode.com/todos
Future<List<SubCategoryObject>> getData() async
final res =
await http.get(Uri.https("jsonplaceholder.typicode.com", "todos"));
if (res.statusCode == 200)
dynamic result = jsonDecode(res.body);
return (result as List).map((e) => SubCategoryObject.fromJson(e)).toList();
else
// If that call was not successful, throw an error.
throw Exception('Failed to load ');
【讨论】:
以上是关于Flutter 错误:期望一个类型为“Map<String, dynamic>”的值,但出现了一个类型为“List<dynamic>”的值的主要内容,如果未能解决你的问题,请参考以下文章
Flutter - 参数类型“Object”不能分配给参数类型“Map<String, dynamic>”
Flutter Qs:未处理的异常:“String”类型不是“FutureOr<Map<String, dynamic>>”类型的子类型
如何修复 Flutter 需要一个“Map<String, dynamic>”类型的值,但得到一个“List<dynamic>”类型的值
Flutter-Firestore “参数类型 'Map<String, dynamic> Function()' 不能分配给参数类型 'Map<String, dynamic>
Flutter 中的 Json 解析:List<dynamic> 不是 'Map<String,dynamic>' 类型的子类型