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

Flutter 文件保存技术问询:如何存储包含int的对象列表?

解决Flutter中存储包含int的对象列表的问题

Hey there! 从你的描述来看,你已经在Flutter路上迈出了不错的一步,自己动手做测试学习类App超棒的!针对你说的「存储包含int的对象列表」这个需求,我给你两个实用的方案,都是Flutter开发里常用的,适配不同的场景:

方案一:用shared_preferences轻量存储(适合数据量小的场景)

shared_preferences是Flutter官方推荐的轻量级键值存储工具,虽然它本身只能存基本类型(比如int、String)和简单集合,但咱可以通过JSON序列化把对象列表转成字符串来存储,完美适配你的需求。

具体步骤:

  1. 先在pubspec.yaml里添加依赖:
dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2
  json_annotation: ^4.8.1
dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0
  1. 定义你的数据类,并且实现JSON序列化/反序列化:
    比如你要存的是一个学习条目对象,包含int类型的id和其他字段:
import 'package:json_annotation/json_annotation.dart';

part 'study_item.g.dart';

@JsonSerializable()
class StudyItem {
  final int id;
  final String title;
  final int progress;

  StudyItem({required this.id, required this.title, required this.progress});

  // 把对象转成Map
  Map<String, dynamic> toJson() => _$StudyItemToJson(this);

  // 从Map转成对象
  factory StudyItem.fromJson(Map<String, dynamic> json) => _$StudyItemFromJson(json);
}

然后在终端运行命令生成序列化代码:

flutter pub run build_runner build
  1. 实现保存和读取列表的方法:
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

// 保存对象列表
Future<void> saveStudyItems(List<StudyItem> items) async {
  final prefs = await SharedPreferences.getInstance();
  // 把每个对象转成Map,再转成JSON字符串
  final String jsonString = jsonEncode(items.map((item) => item.toJson()).toList());
  await prefs.setString('study_items', jsonString);
}

// 读取对象列表
Future<List<StudyItem>> getStudyItems() async {
  final prefs = await SharedPreferences.getInstance();
  final String? jsonString = prefs.getString('study_items');
  if (jsonString == null) {
    return []; // 没有数据返回空列表
  }
  // 把JSON字符串转成Map列表,再转成StudyItem对象列表
  final List<dynamic> jsonList = jsonDecode(jsonString);
  return jsonList.map((json) => StudyItem.fromJson(json)).toList();
}

这样你就可以调用这两个方法来保存和读取你的对象列表啦!

方案二:用sqflite本地数据库(适合数据量大/需要复杂查询的场景)

如果你的学习类App以后会有大量数据,或者需要按条件查询、修改单个条目,那sqflite(本地SQLite数据库)会更合适,它能支持复杂的数据操作。

具体步骤:

  1. 添加依赖:
dependencies:
  flutter:
    sdk: flutter
  sqflite: ^2.3.0
  path_provider: ^2.1.1
  1. 创建数据库和表:
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;

  DatabaseHelper._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('study_database.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getApplicationDocumentsDirectory();
    final path = join(dbPath.path, filePath);

    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future<void> _createDB(Database db, int version) async {
    // 创建表,包含int类型的id、progress等字段
    await db.execute('''
      CREATE TABLE study_items(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        progress INTEGER NOT NULL
      )
    ''');
  }
}
  1. 实现保存和读取列表的方法:
// 插入单个条目
Future<int> insertStudyItem(StudyItem item) async {
  final db = await DatabaseHelper.instance.database;
  return await db.insert('study_items', item.toJson());
}

// 保存整个列表(可以先清空旧数据再插入新的)
Future<void> saveStudyItems(List<StudyItem> items) async {
  final db = await DatabaseHelper.instance.database;
  final batch = db.batch();
  await db.delete('study_items'); // 清空旧数据
  for (var item in items) {
    batch.insert('study_items', item.toJson());
  }
  await batch.commit();
}

// 读取所有条目
Future<List<StudyItem>> getStudyItems() async {
  final db = await DatabaseHelper.instance.database;
  final List<Map<String, dynamic>> maps = await db.query('study_items');
  return List.generate(maps.length, (i) {
    return StudyItem(
      id: maps[i]['id'],
      title: maps[i]['title'],
      progress: maps[i]['progress'],
    );
  });
}

这个方案更适合长期的数据管理,如果你以后要加删除、修改单个条目的功能也很方便。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:49:39