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

Flutter报错:期望'String'类型,实际获取'Null'问题求助

问题分析

这个错误本质是你在Text组件里传入了null值,但Text要求必须是非null的String类型。根源大概率是从Loading页面跳转时参数没传对,或者Home页面获取参数的方式有问题,导致拿到的location/time为null。

排查与修复步骤

1. 检查Loading页面的跳转代码

确保跳转时确实传递了location和time参数,且值不为null。
如果是直接传参给Home构造函数:

Navigator.pushReplacement(context, MaterialPageRoute(
  builder: (context) => Home(
    location: 'London', // 必须是非null的String
    time: '12:00',      // 同样不能为null
  )
));

如果用命名路由传arguments:

Navigator.pushReplacementNamed(context, '/home', arguments: {
  'location': 'London',
  'time': '12:00'
});

2. 检查Home页面获取参数的代码

构造函数传参场景

确保Home类的构造函数正确接收必填参数:

class Home extends StatefulWidget {
  final String location;
  final String time;

  const Home({super.key, required this.location, required this.time});

  @override
  _HomeState createState() => _HomeState();
}

随后在build中直接使用:

Text(widget.location),
Text(widget.time),

ModalRoute获取arguments场景

必须做非空校验,避免拿到null:

@override
Widget build(BuildContext context) {
  final args = ModalRoute.of(context)?.settings.arguments as Map<String, String>?;
  // 用??运算符给null值设置默认字符串
  String location = args?['location'] ?? '未知地点';
  String time = args?['time'] ?? '未知时间';

  return Scaffold(
    body: Column(
      children: [
        Text(location),
        Text(time),
      ],
    ),
  );
}

3. 检查world_time.dart的数据逻辑

如果location/time是从WorldTime类获取的,要确保方法返回非null值,比如处理API请求失败的情况:

class WorldTime {
  String location;
  String time;

  WorldTime({required this.location, required this.time});

  Future<void> getTime() async {
    try {
      // 这里写API请求逻辑
      time = '获取到的时间';
    } catch (e) {
      time = '无法获取时间'; // 避免time变为null
    }
  }
}

在Loading页面调用getTime()后,确认location和time都被正确赋值再跳转。

关键注意点
  • 永远不要给Text组件传null值,要么确保参数非null,要么用??提供默认值
  • 构造函数里的必填参数要加required,避免实例化时漏传
  • 使用ModalRoute获取参数时,必须做非空判断,因为ModalRoute.of(context)和arguments都可能返回null

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:37:06