Flutter笔记应用:如何将TextFormField输入数据本地存储并读写?
Flutter笔记应用本地存储实现方案
针对你的笔记应用重启后数据丢失的问题,下面提供三种常用的本地存储实现方案,根据你的需求选择即可:
1. SharedPreferences(适合简单键值对存储)
适合笔记数量少、结构简单的场景,通过将笔记列表序列化为JSON字符串存储。
步骤:
添加依赖到
pubspec.yaml:dependencies: shared_preferences: ^2.2.2 json_annotation: ^4.8.1 dev_dependencies: build_runner: ^2.4.4 json_serializable: ^6.7.0定义笔记模型并生成序列化代码:
import 'package:json_annotation/json_annotation.dart'; part 'note.g.dart'; @JsonSerializable() class Note { final String id; final String title; final String content; final DateTime createdAt; Note({ required this.id, required this.title, required this.content, required this.createdAt, }); factory Note.fromJson(Map<String, dynamic> json) => _$NoteFromJson(json); Map<String, dynamic> toJson() => _$NoteToJson(this); }运行命令生成序列化代码:
flutter pub run build_runner build实现存储操作:
import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert'; class NoteStorage { static const String _key = 'notes'; // 保存笔记列表 static Future<void> saveNotes(List<Note> notes) async { final prefs = await SharedPreferences.getInstance(); final jsonString = json.encode(notes.map((note) => note.toJson()).toList()); await prefs.setString(_key, jsonString); } // 读取笔记列表 static Future<List<Note>> getNotes() async { final prefs = await SharedPreferences.getInstance(); final jsonString = prefs.getString(_key); if (jsonString == null) return []; final List<dynamic> jsonList = json.decode(jsonString); return jsonList.map((json) => Note.fromJson(json)).toList(); } // 添加新笔记 static Future<void> addNote(Note note) async { final notes = await getNotes(); notes.add(note); await saveNotes(notes); } // 删除笔记 static Future<void> deleteNote(String id) async { final notes = await getNotes(); notes.removeWhere((note) => note.id == id); await saveNotes(notes); } }
2. Hive(轻量级NoSQL存储)
适合需要存储复杂对象、性能要求较高的场景,无需序列化JSON,直接存储对象。
步骤:
添加依赖到
pubspec.yaml:dependencies: hive: ^2.2.3 hive_flutter: ^1.1.0 dev_dependencies: hive_generator: ^1.1.5 build_runner: ^2.4.4初始化Hive:
import 'package:hive_flutter/hive_flutter.dart'; void main() async { await Hive.initFlutter(); Hive.registerAdapter(NoteAdapter()); // 需要生成Adapter await Hive.openBox<Note>('notes'); runApp(MyApp()); }定义笔记模型并生成Adapter:
import 'package:hive/hive.dart'; part 'note.g.dart'; @HiveType(typeId: 0) class Note extends HiveObject { @HiveField(0) String id; @HiveField(1) String title; @HiveField(2) String content; @HiveField(3) DateTime createdAt; Note({ required this.id, required this.title, required this.content, required this.createdAt, }); }运行命令生成Adapter:
flutter pub run build_runner build实现存储操作:
import 'package:hive/hive.dart'; class NoteStorage { static final Box<Note> _box = Hive.box<Note>('notes'); // 获取所有笔记 static List<Note> getNotes() => _box.values.toList(); // 添加笔记 static Future<void> addNote(Note note) async { await _box.add(note); } // 更新笔记 static Future<void> updateNote(int index, Note note) async { await _box.putAt(index, note); } // 删除笔记 static Future<void> deleteNote(int index) async { await _box.deleteAt(index); } }
3. Sqflite(SQLite数据库)
适合笔记数量多、需要复杂查询的结构化数据场景。
步骤:
添加依赖到
pubspec.yaml:dependencies: sqflite: ^2.3.0 path_provider: ^2.1.1初始化数据库:
import 'package:sqflite/sqflite.dart'; import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart'; class DatabaseHelper { static final _databaseName = 'notes.db'; static final _databaseVersion = 1; static final table = 'notes'; static final columnId = '_id'; static final columnTitle = 'title'; static final columnContent = 'content'; static final columnCreatedAt = 'created_at'; // 单例 DatabaseHelper._privateConstructor(); static final DatabaseHelper instance = DatabaseHelper._privateConstructor(); static Database? _database; Future<Database> get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; } _initDatabase() async { final documentsDirectory = await getApplicationDocumentsDirectory(); final path = join(documentsDirectory.path, _databaseName); return await openDatabase(path, version: _databaseVersion, onCreate: _onCreate); } Future _onCreate(Database db, int version) async { await db.execute(''' CREATE TABLE $table ( $columnId TEXT PRIMARY KEY, $columnTitle TEXT NOT NULL, $columnContent TEXT NOT NULL, $columnCreatedAt INTEGER NOT NULL ) '''); } }实现CRUD操作:
import 'package:sqflite/sqflite.dart'; import '../models/note.dart'; import 'database_helper.dart'; class NoteStorage { // 添加笔记 static Future<int> insertNote(Note note) async { final db = await DatabaseHelper.instance.database; return await db.insert(DatabaseHelper.table, { '_id': note.id, 'title': note.title, 'content': note.content, 'created_at': note.createdAt.millisecondsSinceEpoch, }); } // 获取所有笔记 static Future<List<Note>> getNotes() async { final db = await DatabaseHelper.instance.database; final List<Map<String, dynamic>> maps = await db.query(DatabaseHelper.table); return List.generate(maps.length, (i) { return Note( id: maps[i]['_id'], title: maps[i]['title'], content: maps[i]['content'], createdAt: DateTime.fromMillisecondsSinceEpoch(maps[i]['created_at']), ); }); } // 更新笔记 static Future<int> updateNote(Note note) async { final db = await DatabaseHelper.instance.database; return await db.update(DatabaseHelper.table, { 'title': note.title, 'content': note.content, }, where: '_id = ?', whereArgs: [note.id]); } // 删除笔记 static Future<int> deleteNote(String id) async { final db = await DatabaseHelper.instance.database; return await db.delete(DatabaseHelper.table, where: '_id = ?', whereArgs: [id]); } }
使用建议:
- 笔记数量少、结构简单:选SharedPreferences
- 需要快速存取复杂对象:选Hive
- 笔记数量多、需要多条件查询:选Sqflite
内容的提问来源于stack exchange,提问作者Atharva Kelkar
相关产品推荐
相关产品推荐

