当前位置: 首页 > 知识库问答 >
问题:

错误:当我运行时,类型列表不是类型映射的子类型

宓茂才
2023-03-14

我想在我的主页上显示我的JSON数据,但我有一个问题。当我运行时,出现一条错误消息“以下类型错误被抛出构建FutureBuilder(脏,状态:_FutureBuilderState#d0e99):”和(错误:类型“List”不是类型“Map”的子类型

下面是我的示例JSON片段(注意:这是本地JSON):

{
  "restaurants": [{
      "id": "rqdv5juczeskfw1e867",
      "name": "Melting Pot",
      "description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.",
      "pictureId": "https://restaurant-api.dicoding.dev/images/medium/14",
      "city": "Medan",
      "rating": 4.2,
      "menus": {
        "foods": [{
            "name": "Paket rosemary"
          },
          {
            "name": "Toastie salmon"
          },
          {
            "name": "Bebek crepes"
          },
          {
            "name": "Salad lengkeng"
          }
        ],
        "drinks": [{
            "name": "Es krim"
          },
          {
            "name": "Sirup"
          },
          {
            "name": "Jus apel"
          },
          {
            "name": "Jus jeruk"
          },
          {
            "name": "Coklat panas"
          },
          {
            "name": "Air"
          },
          {
            "name": "Es kopi"
          },
          {
            "name": "Jus alpukat"
          },
          {
            "name": "Jus mangga"
          },
          {
            "name": "Teh manis"
          },
          {
            "name": "Kopi espresso"
          },
          {
            "name": "Minuman soda"
          },
          {
            "name": "Jus tomat"
          }
        ]
      }
    },
]
}

以下是我的餐厅档案:

import 'dart:convert';

class RestaurantDetail {
  late Restaurant restaurants;

  RestaurantDetail({required this.restaurants});

  RestaurantDetail.fromJson(Map<String, dynamic> json) {
    restaurants = Restaurant.fromJson(json['restaurants']);
  }
}

class Restaurant {
  late String id;
  late String name;
  late String description;
  late String pictureId;
  late String city;
  late double rating;
  late Menus menus;

  Restaurant({
    required this.id,
    required this.name,
    required this.description,
    required this.pictureId,
    required this.city,
    required this.rating,
    required this.menus,
  });

  Restaurant.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    description = json['description'];
    pictureId = json['pictureId'];
    city = json['city'];
    rating = json['rating'];
    menus = Menus.fromJson(json['menus']);
  }
}

class Menus {
  late Foods foods;
  late Drinks drinks;

  Menus({
    required this.foods,
    required this.drinks,
  });

  Menus.fromJson(Map<String, dynamic> json) {
    foods = Foods.fromJson(json['foods']);
    drinks = Drinks.fromJson(json['drinks']);
  }
}

class Foods {
  late String name;

  Foods({required this.name});

  Foods.fromJson(Map<String, dynamic> json) {
    name = json['name'];
  }
}

class Drinks {
  late String name;

  Drinks({required this.name});

  Drinks.fromJson(Map<String, dynamic> json) {
    name = json['name'];
  }
}

List<RestaurantDetail> parseRestaurant(String? json) {
  if (json == null) {
    return [];
  }

  final List parsed = jsonDecode(json);
  return parsed.map((json) => RestaurantDetail.fromJson(json)).toList();
}

下面是主页代码:

import 'package:flutter/material.dart';
import 'package:restaurant/data/restaurant.dart';
import 'package:restaurant/style/theme.dart';

class HomePage extends StatelessWidget {
  static const routeName = '/article_list';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kBackgroundColor,
      body: FutureBuilder<String>(
        future: DefaultAssetBundle.of(context)
            .loadString('assets/local_restaurant.json'),
        builder: (context, snapshot) {
          final List<RestaurantDetail> restaurants =
              parseRestaurant(snapshot.data);
          return ListView.builder(
            itemCount: restaurants.length,
            itemBuilder: (context, index) {
              return _buildRestaurantItem(context, restaurants[index]);
            },
          );
        },
      ),
    );
  }

  Widget _buildRestaurantItem(
      BuildContext context, RestaurantDetail restaurantDetail) {
    return ListTile(
      contentPadding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      leading: Image.network(
        restaurantDetail.restaurants.pictureId,
        width: 100,
      ),
      title: Text(restaurantDetail.restaurants.name),
      subtitle: Text(restaurantDetail.restaurants.city),
      onTap: () {},
    );
  }
}

共有1个答案

蒋高超
2023-03-14

几点注意事项:

>

  • 根据您的错误错误:

    类型“List”不是类型“Map”的子类型

    这是对响应的原因,你实际上收到了一个列表。

    [ /// <--- square bracket means list as you probably know.
      {
      "restaurants": [
    

    原始输入

    class Menus {
      late Foods foods;
      late Drinks drinks;
    
      Menus({
        required this.foods,
        required this.drinks,
      });
    
      Menus.fromJson(Map<String, dynamic> json) {
        foods = Foods.fromJson(json['foods']);
        drinks = Drinks.fromJson(json['drinks']);
      }
    }
    

    新输入

    class Menus {
      late List<Foods> foods = <Foods>[];
      late List<Drinks> drinks = <Drinks>[];
    
      Menus({
        required this.foods,
        required this.drinks,
      });
    
      Menus.fromJson(Map<String, dynamic> json) {
        for (final _foods in json["foods"]) {
          foods.add(Foods.fromJson(_foods));
        }
        for (final _drinks in json["drinks"]) {
          drinks.add(Drinks.fromJson(_drinks));
        }
      }
    }
    

    实例

    void updateValueKeyFromList(list, key, newValue){
       list.update(key, existingValue, newValue);
    }
    
    late List<Drinks> drinks = <Drinks>[]; ///empty list
    

    我实际上不知道你的api的正确反应,但这可能会帮助你得到一个想法

    import 'dart:convert';
    
    void main() {
      final restaurants = RestaurantDetail.fromJson(apiResponse).restaurants;
      for (final _restaurant in restaurants){
         print(_restaurant.id);
      }
     
    }
    
    class RestaurantDetail {
      late List<Restaurant> restaurants = <Restaurant>[];
    
      RestaurantDetail({required this.restaurants});
    
      RestaurantDetail.fromJson(Map<String, dynamic> json) {
        for (final _restaurant in json["restaurants"]) {
          restaurants.add(Restaurant.fromJson(_restaurant));
        }
      }
    }
    
    class Restaurant {
      late String id;
      late String name;
      late String description;
      late String pictureId;
      late String city;
      late double rating;
      late Menus menus;
    
      Restaurant({
        required this.id,
        required this.name,
        required this.description,
        required this.pictureId,
        required this.city,
        required this.rating,
        required this.menus,
      });
    
      Restaurant.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
        description = json['description'];
        pictureId = json['pictureId'];
        city = json['city'];
        rating = json['rating'];
        menus = Menus.fromJson(json['menus']);
      }
    }
    
    class Menus {
      late List<Foods> foods = <Foods>[];
      late List<Drinks> drinks = <Drinks>[];
    
      Menus({
        required this.foods,
        required this.drinks,
      });
    
      Menus.fromJson(Map<String, dynamic> json) {
        for (final _foods in json["foods"]) {
          foods.add(Foods.fromJson(_foods));
        }
        for (final _drinks in json["drinks"]) {
          drinks.add(Drinks.fromJson(_drinks));
        }
      }
    }
    
    class Foods {
      late String name;
    
      Foods({required this.name});
    
      Foods.fromJson(Map<String, dynamic> json) {
        name = json['name'];
      }
    }
    
    class Drinks {
      late String name;
    
      Drinks({required this.name});
    
      Drinks.fromJson(Map<String, dynamic> json) {
        name = json['name'];
      }
    }
    
    List<RestaurantDetail> parseRestaurant(String? json) {
      if (json == null) {
        return [];
      }
    
      final List parsed = jsonDecode(json);
      return parsed.map((json) => RestaurantDetail.fromJson(json)).toList();
    }
    
    Map<String, dynamic> apiResponse = {
      "restaurants": [
        {
          "id": "rqdv5juczeskfw1e867",
          "name": "Melting Pot",
          "description":
              "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.",
          "pictureId": "https://restaurant-api.dicoding.dev/images/medium/14",
          "city": "Medan",
          "rating": 4.2,
          "menus": {
            "foods": [
              {"name": "Paket rosemary"},
              {"name": "Toastie salmon"},
              {"name": "Bebek crepes"},
              {"name": "Salad lengkeng"}
            ],
            "drinks": [
              {"name": "Es krim"},
              {"name": "Sirup"},
              {"name": "Jus apel"},
              {"name": "Jus jeruk"},
              {"name": "Coklat panas"},
              {"name": "Air"},
              {"name": "Es kopi"},
              {"name": "Jus alpukat"},
              {"name": "Jus mangga"},
              {"name": "Teh manis"},
              {"name": "Kopi espresso"},
              {"name": "Minuman soda"},
              {"name": "Jus tomat"}
            ]
          }
        }
      ]
    };
    
    

  •  类似资料:
    • 因此,我创建了一个应用程序,通过api读取数据,并尝试解析JSON api 这是我的错误截图 我试着把它改成一个列表,但它仍然读取一个错误 这是我的密码大象。飞奔 如何纠正此错误?请帮忙

    • 我试图获得用户信息后,用户输入电子邮件和密码。我使用的api会返回我用户的额外信息,所以我尝试从中获取这些信息。 我试图解析这个json: 这些是我的模型: 这是我发送电子邮件、密码和获取用户数据的部分: 这是给我错误的部分 我打印了响应体,它给出了我想要的字符串,但是jsonDecode返回了一个列表,所以我不能使用它。我怎样才能解决这个问题?提前谢谢。

    • 我目前正在构建一个通过api读取数据的应用程序,我正在尝试从JSON占位符解析JSON api。 我为用户(users_future_model.dart)做了一个模型类: 这是将json读入小部件的main.dart: 这是我试图阅读的JSON信息,尽管它只是其中的一小部分: 我当前遇到的错误是: 如何纠正此错误?

    • 我正面临着一个奇怪的颤动错误。我使用json序列化。 这是我的密码 我的web api发送的数据如下 这是数组的数组。 生成错误的代码是 它给出的错误 JSON数据这里是JSON数据格式的屏幕截图

    • 当我尝试解码json时,它会给我错误。 我的模范班 功能在我使用它的地方 json数据

    • 我对Flutter编程非常陌生,我正在尝试导入一个本地JSON文件,其中包含书籍数据,如标题、作者、发布年份等。 最初我使用JSON-to-DART转换器来组装一个图书数据模型,现在我正在尝试创建一个函数,在该函数中,程序获取本地JSON文件,并使用类中的方法将数据解析为地图。 我遇到的问题是返回类型