json - 错误:输入'_InternalLinkedHashMap' 不是类型 'List 的子类型'
问题描述
我是 Flutter 的新手,我尝试读取这个 json 文件,但得到错误“像类型列表动态不是类型“列表”的子类型。”
请帮助我遵循有用的教程并告诉我如何修复此代码。
这是我的代码: resto_list_page.dart
import 'package:flutter/material.dart';
import 'resto.dart';
class RestoListPage extends StatelessWidget {
static const routeName = '/resto_list';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Restaurant App'),
),
body: FutureBuilder<dynamic>(
future: DefaultAssetBundle.of(context)
.loadString('assets/local_restaurant.json'),
builder: (context, snapshot) {
final List<Resto> restos = parseArticles(snapshot.data);
return ListView.builder(
itemCount: restos.length,
itemBuilder: (context, index) {
return _buildArticleItem(context, restos[index]);
},
);
},
),
);
}
}
Widget _buildArticleItem(BuildContext context, Resto resto) {
return ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
leading: Image.network(
resto.pictureId,
width: 100,
),
title: Text(resto.name),
subtitle: Column(
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.place),
Text(resto.city)
],
),
Row(
children: <Widget>[
Icon(Icons.star),
Text('$resto.rating')
],
),
],
),
);
}
这是另一个文件代码。 恢复.dart
import 'dart:convert';
class Resto {
String id;
String name;
String description;
String pictureId;
String city;
double rating;
Map<String, String> foods;
Map<String, String> drinks;
Resto(
{this.id,
this.name,
this.description,
this.pictureId,
this.city,
this.rating,
this.foods,
this.drinks});
Resto.fromJson(Map<String, dynamic> restos) {
id = restos['id'];
name = restos['name'];
description = restos['description'];
pictureId = restos['pictureId'];
city = restos['city'];
rating = restos['rating'];
foods = restos['menus']['foods'];
drinks = restos['menus']['drinks'];
}
}
List<Resto> parseArticles(String json) {
if (json == null) {
return [];
}
final List parsed = jsonDecode(json);
return parsed.map((json) => Resto.fromJson(json)).toList();
}
解决方案
parsed
必须声明为List<dynamic>
:
final List<dynamic> parsed = jsonDecode(json);
所以完整的代码变成了:
List<Resto> parseArticles(String json) {
if (json == null) {
return [];
}
final List<dynamic> parsed = jsonDecode(json);
return parsed.map((json) => Resto.fromJson(json)).toList();
}
推荐阅读
- javascript - Javascript 中的缩小功能不起作用,但在启用源映射时起作用
- ruby-on-rails - 将 curl 重写为 HTTP POST 请求以获取访问令牌
- javascript - Puppeteer:如何将对象传递给 page.evaluate?
- python - 当文件没有所需的权限时抛出异常
- javascript - 如何将状态标志存储为 GLSL / WebGL 的浮点数
- java - 监视自注入 bean
- apache-spark - 在 pyspark 中设置 log4j 属性
- directory - 如何在 App Maker 中自动记录用户名
- linux-kernel - 如何在 linux 内核源代码中关闭内核页表隔离功能?
- android - Android Google Place API 错误状态{statusCode=PLACES_API_ACCESS_NOT_CONFIGURED, resolution=null}