You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错:'_Map<String, dynamic>'不是'List<dynamic>'子类型,求解决

错误原因分析

你遇到的'_Map<String, dynamic>' is not a subtype of type 'List<dynamic>'错误,核心原因是接口返回的是单个JSON对象(Map结构),但你的代码错误地将其当作JSON数组(List)来解析。

你提供的接口返回数据是单个Post对象:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

而AppRepostry里的getApp方法却把解析结果强转为List,这就导致了类型不匹配错误。


解决方案

1. 修改仓库代码(AppRepostry)

因为接口返回单个对象,所以方法返回值改为Future<UserModel>,解析时直接处理单个Map:

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../model/user_model.dart';

String appUrl = "https://jsonplaceholder.typicode.com/posts/1";

class AppRepostry {
  Future<UserModel> getApp() async {
    http.Response response = await http.get(Uri.parse(appUrl));

    if (response.statusCode == 200) {
      final Map<String, dynamic> result = jsonDecode(response.body);
      return UserModel.fromJson(result);
    } else {
      throw Exception(response.reasonPhrase);
    }
  }
}

2. 调整Bloc逻辑

如果你的Bloc原本处理列表数据,现在需要适配单个对象:

  • 将LoadedAppState中的apps字段类型从List<UserModel>改为UserModel;
  • 在Bloc的事件处理中,调用getApp后生成单个对象的状态。

示例修改后的状态类:

class LoadedAppState extends UsreState {
  final UserModel app;
  LoadedAppState(this.app);
}

3. 调整UI代码(HomePage)

适配单个对象的状态,若仍想用ListView展示,可将单个对象包装成List:

if (state is LoadedAppState) {
  List<UserModel> usermodel = [state.app]; // 包装成List
  return ListView.builder(
      itemCount: usermodel.length,
      itemBuilder: (_, index) {
        return Padding(
          padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
          child: Card(
            color: Colors.deepPurpleAccent,
            child: ListTile(
              title: Text('${usermodel[index].title}'),
            ),
          ),
        );
      });
}

或者直接展示单个对象,无需ListView:

if (state is LoadedAppState) {
  UserModel usermodel = state.app;
  return Padding(
    padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
    child: Card(
      color: Colors.deepPurpleAccent,
      child: ListTile(
        title: Text('${usermodel.title}'),
      ),
    ),
  );
}

内容的提问来源于stack exchange,提问作者doretos al

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:01:31