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

Flutter中Color转JSON存储读取报错:Null不是int子类型

问题:Flutter保存Color为int到JSON后读取报错:type 'Null' is not a subtype of type 'int'

错误原因

报错核心是旧的JSON数据中没有backgroundColor字段:当读取时jsonData['backgroundColor']返回null,但JournalEntry类的backgroundColor是不可为null的int类型,直接赋值null就会触发类型转换错误。

另外还有一个潜在问题:showDialog的返回值可能为null(比如用户点击返回键而非OK按钮),你现在直接赋值给非空的Color selectedColor,会导致运行时错误,需要一并修复。

解决方案

1. 兼容旧JSON数据,读取时给默认值

在加载JSON数据时,给backgroundColor字段加上默认值,避免null赋值给int类型:

修改journal_data_manager.dart中的加载代码:

loadJournalEntries.add(JournalEntry(
    title: jsonData['title'],
    content: jsonData['content'],
    dateTime: DateTime.parse(jsonData['dateTime']),
    filePath: filePath,
    backgroundColor: jsonData['backgroundColor'] ?? 0xFF879d55, // 补充默认值
));

2. 修复showDialog的返回值处理

showDialog可能返回null,需要将selectedColor声明为可空类型,再做判断:

修改create_journal.dart中的_showColorPickerDialog方法:

Future<void> _showColorPickerDialog() async {
    Color? selectedColor = await showDialog( // 改为可空类型Color?
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Select Background Color'),
          content: SingleChildScrollView(
            child: MaterialPicker(
              pickerColor: _selectedBackgroundColor,
              onColorChanged: (Color color) {
                setState(() {
                  _selectedBackgroundColor = color;
                });
              },
              enableLabel: true,
            ),
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop(_selectedBackgroundColor);
              },
              child: const Text('OK'),
            ),
          ],
        );
      },
    );

    if (selectedColor != null) {
      setState(() {
        _selectedBackgroundColor = selectedColor;
      });
    }
  }

3. 修复保存逻辑的日期字段(可选)

在journal_data_manager.dart的saveEntry方法中,timeISOString是未定义变量,应该改为使用entry的日期:

String jsonString = jsonEncode({
  'dateTime': entry.strDateTime, // 替换为entry的日期字段
  'title': entry.title,
  'content': entry.content,
  'backgroundColor': entry.backgroundColor,
});

额外建议

如果后续需要处理更多复杂的JSON序列化/反序列化,建议使用json_serializable包,它能自动处理null安全和默认值,减少手动编写序列化代码的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:43:17