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

Flutter报错:type Null is not a subtype of type 'String'求助

报错排查:type Null is not a subtype of type 'String'

问题描述

运行代码时触发错误:type Null is not a subtype of type 'String',场景是从API获取数据后在Center组件的ListView中展示,该逻辑此前在其他模型中可正常运行。相关代码及错误截图如下:

模型代码

import 'package:meta/meta.dart';
import 'dart:convert';

class PlanningCoach {
  final int? idPc;
  final double? prixPc;
  final DateTime? datePc;
  final String? horairePc;
  final int? nbpPc;
  final int? idcoach;
  final bool? recylcebin;
  PlanningCoach({
    required this.idPc,
    required this.prixPc,
    required this.datePc,
    required this.horairePc,
    required this.nbpPc,
    required this.idcoach,
    required this.recylcebin,
  });
  factory PlanningCoach.fromJson(Map<String, dynamic> json) => PlanningCoach(
        idPc: json["id_pc"],
        prixPc: json["prix_pc"],
        datePc: DateTime.parse(json["date_pc"]),
        horairePc: json["horaire_pc"],
        nbpPc: json["nbp_pc"],
        idcoach: json["idcoach"],
        recylcebin: json["recylcebin"],
      );
}

数据请求与展示代码

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class DetailGroundScreen extends StatefulWidget {
  const DetailGroundScreen({Key? key}) : super(key: key);
  @override
  _DetailGroundScreenState createState() => _DetailGroundScreenState();
}
class _DetailGroundScreenState extends State<DetailGroundScreen> {
  late Future<List<PlanningCoach>> futurePCoach;

  Future<List<PlanningCoach>> fetchPlanningCoach() async {
    final response = await http.get(Uri.parse(
        'http://smart.netrostercloud.com/smartcoach/api/plannningcoaches/displayPlanningCoach'));

    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.body);
      return jsonResponse
          .map((data) => PlanningCoach.fromJson(data))
          .toList();
    } else {
      throw Exception('Failed to load coach');
    }
  }

  @override
  void initState() {
    super.initState();
    futurePCoach = fetchPlanningCoach();
  }

  @override
  Widget build(BuildContext context) {
    final value = ModalRoute.of(context)!.settings.arguments;
    return Center(
      child: FutureBuilder<List<PlanningCoach>>(
        future: futurePCoach,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<PlanningCoach>? data = snapshot.data;
            return ListView.builder(
                shrinkWrap: true,
                itemCount: data?.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    height: 75,
                    color: Colors.white,
                    child: Center(
                      child: Text('${data![index].idPc}'),
                    ),
                  );
                });
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}

错误截图

错误截图

问题原因

报错核心是API返回的date_pc字段存在null值,但代码中直接调用DateTime.parse(json["date_pc"])——该方法要求传入非null的String类型参数,当传入null时就会触发Null is not a subtype of type 'String'的类型转换错误。

另外代码中还存在潜在风险:

  • prixPc字段如果API返回的是int类型,直接赋值给double?可能触发类型错误
  • ListView的itemCount使用data?.length,当data为null时会导致itemCount为null,可能引发异常
  • Text组件中强制使用data![index].idPc,如果data或idPc为null会触发空指针

解决方案

1. 修复DateTime解析的空值问题

修改PlanningCoach.fromJson方法中datePc的赋值逻辑,先判断字段是否为null再解析:

factory PlanningCoach.fromJson(Map<String, dynamic> json) => PlanningCoach(
      idPc: json["id_pc"],
      prixPc: json["prix_pc"]?.toDouble(), // 处理int转double的情况
      datePc: json["date_pc"] != null ? DateTime.parse(json["date_pc"]) : null,
      horairePc: json["horaire_pc"],
      nbpPc: json["nbp_pc"],
      idcoach: json["idcoach"],
      recylcebin: json["recylcebin"],
    );

2. 优化页面代码的空安全处理

修改ListView相关逻辑,避免空值引发的异常:

if (snapshot.hasData) {
  List<PlanningCoach>? data = snapshot.data;
  return ListView.builder(
      shrinkWrap: true,
      itemCount: data?.length ?? 0, // 空值时默认0
      itemBuilder: (BuildContext context, int index) {
        final item = data![index];
        return Container(
          height: 75,
          color: Colors.white,
          child: Center(
            child: Text(item.idPc?.toString() ?? "无ID"), // 空值时显示默认文本
          ),
        );
      });
}

3. 调试建议

可以在fetchPlanningCoach方法中打印API返回的原始数据,确认具体哪个字段存在null值:

if (response.statusCode == 200) {
  print("API返回数据: ${response.body}"); // 打印原始数据
  List jsonResponse = json.decode(response.body);
  return jsonResponse
      .map((data) => PlanningCoach.fromJson(data))
      .toList();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:24:51