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

Flutter从Map获取location时出现Null与String类型不匹配错误求助

Flutter 解决 'Null' is not a subtype of type 'String' 错误

问题代码

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

class Home extends StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  Map data = {};
  Object? parameters;

  @override
  Widget build(BuildContext context) {

    parameters = ModalRoute.of(context)!.settings.arguments as Map;
    Map data = jsonDecode(jsonEncode(parameters));
    print(data);
    
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            FlatButton.icon(
              onPressed: () {
                Navigator.pushNamed(context,'/location');
              },
              icon: Icon(Icons.edit_location),
              label: Text('Edit Location'),
            ),
            SizedBox(height: 20.0),
            Row(
              children: <Widget>[
                Text(
                  data['location']
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}

错误信息

type 'Null' is not a subtype of type 'String'.

解决方法

  • 检查路由传参完整性
    确保跳转到/home路由时,传递的arguments中包含非空的location字段。示例:

    Navigator.pushNamed(context, '/home', arguments: {'location': 'Shanghai'});
    
  • 添加空值兜底处理
    直接访问data['location']可能返回null,给Text组件添加空值处理:

    // 使用空值合并运算符设置默认值
    Text(data['location'] ?? '未设置地点')
    
    // 或者条件渲染
    data['location'] != null ? Text(data['location']) : const Text('未选择地点')
    
  • 优化参数接收逻辑
    移除多余的jsonDecode(jsonEncode(parameters))操作(这步完全没必要,反而可能引入额外问题),同时避免在build方法中重复解析参数(build会多次执行),改用didChangeDependencies处理:

    @override
    void didChangeDependencies() {
      super.didChangeDependencies();
      final args = ModalRoute.of(context)?.settings.arguments;
      if (args is Map) {
        setState(() {
          data = args;
        });
      }
    }
    
  • 使用类型安全的参数传递
    定义实体类封装参数,避免Map的类型不安全问题:

    // 定义参数类
    class LocationParams {
      final String location;
      LocationParams(this.location);
    }
    
    // 跳转时传递参数
    Navigator.pushNamed(context, '/home', arguments: LocationParams('Guangzhou'));
    
    // 接收并使用参数
    @override
    Widget build(BuildContext context) {
      final params = ModalRoute.of(context)?.settings.arguments as LocationParams?;
      return Scaffold(
        body: SafeArea(
          child: Text(params?.location ?? '默认地点'),
        ),
      );
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:06:17