import 'dart:io'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; class DatabaseHelper { static final DatabaseHelper _instance = DatabaseHelper._internal(); factory DatabaseHelper() => _instance; static Database? _database; DatabaseHelper._internal(); Future get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; } Future _initDatabase() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, 'chat.db'); return await openDatabase( path, version: 1, onCreate: _onCreate, ); } Future _onCreate(Database db, int version) async { await db.execute(''' CREATE TABLE messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, role TEXT NOT NULL, message TEXT NOT NULL, timestamp INTEGER DEFAULT (strftime('%s', 'now')) '''); } // 插入一条消息 Future insertMessage(Map message) async { Database db = await database; return await db.insert('messages', message); } // 获取所有消息(按时间排序) Future>> getMessages() async { Database db = await database; return await db.query('messages', orderBy: 'timestamp ASC'); } // 删除所有消息 Future clearMessages() async { Database db = await database; return await db.delete('messages'); } }