' 不是类型 'List 的子类型',json,api,rest,flutter"/>

首页 > 解决方案 > 错误:输入'_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();
}

标签: jsonapirestflutter

解决方案


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();
}

推荐阅读