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

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

报错原因及解决方案

核心问题

报错type '_Map<String, dynamic>' is not a subtype of type 'List<dynamic>'的根本原因是:
你调用的API返回的是单个文章对象(JSON格式为Map<String, dynamic>),但代码里错误地将其强制解析为List,导致类型转换不匹配。

具体修改步骤

1. 修正API请求解析逻辑

修改ApiServices类的getArticles方法,适配单个对象的返回格式:

import 'dart:convert';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:friendnpal/models/articles_model.dart';
import 'package:http/http.dart';

class ApiServices {
  String endpoint =
      'https://friendnpalapp-production-0d46.up.railway.app/api/article/random_daily';
  // 返回类型改为单个ArticlesModel,不再是List
  Future<ArticlesModel> getArticles() async {
    Response response = await get(Uri.parse(endpoint));

    if (response.statusCode == 200) {
      // 直接解析为Map,再转成单个ArticlesModel对象
      final Map<String, dynamic> result = jsonDecode(response.body);
      print(response.body);
      return ArticlesModel.fromJson(result);
    } else {
      print('error');
      throw Exception(response.reasonPhrase);
    }
  }
}
final articlesProvider = Provider<ApiServices>((ref) => ApiServices());

2. 同步修正FutureProvider定义

假设你的articlesDataProvider是FutureProvider,需要同步修改其返回类型:

final articlesDataProvider = FutureProvider<ArticlesModel>((ref) async {
  return ref.watch(articlesProvider).getArticles();
});

3. 调整UI展示逻辑

因为数据是单个对象而非List,直接渲染内容即可,无需使用ListView.builder:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:friendnpal/models/articles_model.dart';
import '../../../data_provider.dart';
import '../../../in_app_browser/in_app_browser_screen.dart';
import '../../../utils/app_colors.dart';
import '../../../utils/app_strings.dart';

class ArticlesWidget extends ConsumerWidget {
  const ArticlesWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final _data = ref.watch(articlesDataProvider);

    return _data.when(
        data: (article) {
          // 直接使用单个article对象
          return Container(
            padding: const EdgeInsets.fromLTRB(18, 19, 18, 7),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              gradient: const LinearGradient(
                colors: [
                  Color(0xff5F7AFF),
                  Color(0xff04D486),
                ],
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  margin: const EdgeInsets.only(bottom: 24),
                  alignment: Alignment.center,
                  child: const Text(
                    'Article of the day',
                    style: TextStyle(
                        fontSize: 20,
                        color: AppColors.white,
                        fontFamily: AppStrings.fontName),
                  ),
                ),
                Text(
                  article.content!,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 16,
                      color: AppColors.white,
                      fontFamily: AppStrings.fontName),
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => InAppBrowserPage(
                                  articlesList: article, // 传入单个对象
                                )));
                  },
                  child: Container(
                    padding: EdgeInsets.all(10),
                    margin: const EdgeInsets.only(top: 39),
                    decoration: BoxDecoration(
                        color: AppColors.blue,
                        borderRadius: BorderRadius.circular(72)),
                    child: const Text(
                      'Read More',
                      style: TextStyle(
                          fontSize: 15,
                          color: AppColors.white,
                          fontFamily: AppStrings.fontName),
                    ),
                  ),
                )
              ],
            ),
          );
        },
        error: (err, s) => Text(err.toString()),
        loading: () => const Center(
              child: CircularProgressIndicator(),
            ));
  }
}

额外说明

  • 可以通过print(response.body)的输出确认返回格式:{...}代表单个对象,[{...}, {...}]才是数组。
  • 确保ArticlesModel.fromJson方法能正确解析单个Map对象,无针对List的特殊处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:45:08