如何在Flutter中使用Floor存储List<String>类型数据
在Floor中处理List类型的存储(类似Room的TypeConverter)
Floor本身不直接支持List<String>这类复杂数据类型的存储,你需要通过自定义类型转换器来实现,原理和Room的@TypeConverter一致:把List转成数据库能识别的字符串(比如JSON格式),读取时再转回来。
步骤1:创建类型转换器
新建一个转换器类,实现Floor的TypeConverter,负责List<String>和String之间的双向转换:
import 'dart:convert'; import 'package:floor/floor.dart'; class StringListConverter extends TypeConverter<List<String>?, String?> { @override List<String>? decode(String? databaseValue) { if (databaseValue == null) return null; // 把JSON字符串转成List<String> return List<String>.from(jsonDecode(databaseValue)); } @override String? encode(List<String>? value) { if (value == null) return null; // 把List<String>转成JSON字符串 return jsonEncode(value); } }
步骤2:在数据库类中注册转换器
找到你的Floor数据库抽象类,用@TypeConverters注解把刚才的转换器注册进去,这样所有实体类都能使用这个转换器:
import 'package:floor/floor.dart'; // 注册转换器 @TypeConverters([StringListConverter]) @Database(version: 1, entities: [Products]) abstract class AppDatabase extends FloorDatabase { ProductsDao get productsDao; }
步骤3:修改Products实体类
保持images字段的类型不变,不需要额外注解,转换器会自动处理该字段的存储和读取:
@Entity(tableName: articlesTableName) class Products{ @primaryKey int? id; String? title; String? description; int? price; double? discountPercentage; double? rating; int? stock; String? brand; String? category; String? thumbnail; List<String>? images; // 无需额外注解,转换器自动处理 // 构造函数、fromJson、toJson方法保持不变 Products( { this.id, this.title, this.description, this.price, this.discountPercentage, this.rating, this.stock, this.brand, this.category, this.thumbnail, this.images}); Products.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; description = json['description']; price = json['price']; discountPercentage = json['discountPercentage'] == null ? 0.0 : json['discountPercentage'].toDouble(); rating = json['rating'] == null ? 0.0 : json['rating'].toDouble(); stock = json['stock']; brand = json['brand']; category = json['category']; thumbnail = json['thumbnail']; images = json['images'].cast<String>(); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['description'] = this.description; data['price'] = this.price; data['discountPercentage'] = this.discountPercentage; data['rating'] = this.rating; data['stock'] = this.stock; data['brand'] = this.brand; data['category'] = this.category; data['thumbnail'] = this.thumbnail; data['images'] = this.images; return data; } }
步骤4:重新生成Floor代码
执行以下命令重新生成数据库相关代码,此时应该不会再出现“Column type is not supported for List?”的错误:
flutter packages pub run build_runner build
验证逻辑
当你保存Products对象到数据库时,images列表会被自动转成JSON字符串存储;读取时,JSON字符串又会被自动转回List<String>,完全不需要手动处理转换逻辑。
内容的提问来源于stack exchange,提问作者androholic
相关产品推荐
相关产品推荐

