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

Flutter SQLite开发报错:int is not a subtype of string求助

解决SQLite + FutureBuilder 类型转换错误(int 无法转为 string)

问题场景

开发SQLite演示项目时,已创建CategoryModel模型类,在SQLite的onCreate方法中添加了默认分类,尝试通过FutureBuilder在首页展示所有分类,但触发错误分支,提示type int is not a subtype of string,页面显示居中错误文本。

错误原因

核心问题出在totalamount字段的类型处理上:

  1. 原代码将totalamount转为字符串存储到SQLite,但SQLite是弱类型数据库,会自动将"0.0"这类字符串转换为整数类型存储。
  2. 从数据库查询时,totalamount被返回为int类型,而CategoryModel.frommap中使用double.parse(map['totalamount'])尝试将int直接转为字符串解析,导致类型转换错误。
  3. 额外问题:onCreate方法中未使用await处理异步数据库操作,可能导致表未创建完成就执行插入操作,引发潜在异常。

修复方案

调整totalamount的存储和解析逻辑,直接使用数值类型存储,避免字符串转换:

修改后的CategoryModel类

class CategoryModel{
  String title;
  IconData icon;
  int entries;
  double totalamount;

  CategoryModel({required this.title,this.entries=0,required this.icon,this.totalamount=0.0});

  Map<String,dynamic> tomap()
  {
    return {
      'title':title,
      'entries':entries,
      'totalamount':totalamount // 直接存储数值,无需转字符串
    };
  }


  factory CategoryModel.frommap(Map<String,dynamic> map)
  {
    return CategoryModel(
        title: map['title'] as String,
        icon: icons[map['title'] as String] ?? Icons.error, // 增加默认图标,避免空指针
        entries: map['entries'] as int,
        totalamount: (map['totalamount'] as num).toDouble() // 兼容int/double类型,转为double
    );
  }
}

修改后的SqfliteProvider类

class SqfliteProvider {
  static Future<Database> _getdb() async {
    return openDatabase(join(await getDatabasesPath(), 'expensedb1.db'),
        version: 1,
        onCreate: (db,version) async { // 添加async处理异步操作
          // 将totalamount字段类型改为REAL(SQLite的数值类型)
          await db.execute("CREATE TABLE categorytb(title TEXT NOT NULL,entries INTEGER NOT NULL,totalamount REAL NOT NULL)");

          //add some default categories
          print('I am ready to call');
          for(int x=0;x<icons.length;x++)
          {
            await db.insert('categorytb', {
              'title':icons.keys.toList()[x],
              'entries':0,
              'totalamount':0.0 // 直接插入数值
            });
          }
        });
  }

  static Future<List<CategoryModel>?> fetchcategory() async{
    final db=await _getdb();

    List<CategoryModel> templist=[];
    List<Map<String,dynamic>> maplist=await db.query('categorytb');

    print(maplist.toString());

    if(maplist.isEmpty)
      return null;

    templist=maplist.map((e) => CategoryModel.frommap(e)).toList();
    return templist;
  }
}

额外优化点

  • 在Icon获取时增加默认值(Icons.error),避免因icons字典中不存在对应title导致的空指针异常。
  • 所有数据库异步操作添加await,确保执行顺序正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:40:35