Flutter:如何使用SQFlite存储的数据?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter:如何使用SQFlite存储的数据?相关的知识,希望对你有一定的参考价值。
我真的在Flutter和SQFlite上苦苦挣扎。周围有很多复杂的示例,但没有一个简单的示例仅用于获取数据并将其放入变量中以供小部件或模型使用。我尝试了很多示例,但大多数示例都给出错误“表不存在”。我终于找到了一个可以正常工作的示例,并尝试将其满足我的需要,但我只是迷路了。我是个新手,但是不喜欢编码。多年从事网络编码。我浪费了数小时试图仅使一个简单的查询工作并在变量中返回其内容。我真的在考虑完全放弃Flutter,只是因为要处理存储的数据有多困难。这应该是基本的东西。为什么要这么难!
无论如何,这是我的代码,因此您可以看到我正在尝试实现的目标。我可以在DBHelper类中创建数据库,插入数据并获取数据,但是我不知道如何在数据库外部使用该数据。我的目标是得到一个简单的示例来工作,然后可以在整个应用程序中更大规模地实现该示例。我有不同种类的动态列表,等等。任何帮助将不胜感激!
database.dart
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DBNoteModel
String id;
String value;
DBNoteModel(this.id, this.value);
Map<String, dynamic> toMap()
final map = new Map<String, dynamic>();
map["id"] = id;
map["value"] = value;
return map;
//to be used when converting the row into object
factory DBNoteModel.fromMap(Map<String, dynamic> data) =>
new DBNoteModel(id: data['id'], value: data['value']);
class DBHelper
Database db;
DBHelper()
initDatabase();
Future<void> initDatabase() async
db = await openDatabase(join(await getDatabasesPath(), "database.db"),
onCreate: (db, version)
return db.execute('''
CREATE TABLE notes(id TEXT PRIMARY KEY, value TEXT);
INSERT INTO notes (id, value) VALUES ('home', 'asd');
''');
, version: 1);
Future<void> updateNote(String id, String value) async
db.rawUpdate("UPDATE notes SET value = '$value' WHERE id = $id");
getNote(String id) async
List<Map> result = await db.rawQuery("SELECT * FROM notes WHERE id = $id");
if (result.length > 0)
return DBNoteModel.fromMap(result[0]);
return null;
test.dart
import 'package:flutter/material.dart';
import '../../utilities/database.dart';
class TestScreen extends StatelessWidget
@override
Widget build(BuildContext context)
final DBHelper _dbHelper = DBHelper();
var note = _dbHelper.getNote('home');
return Text(note.value);
如果您有多个数据记录,则需要数据模型的List<DBNoteModel>
。在此示例中,它以Listview显示
在数据库的onCreate
命令中,每个命令都需要单独的execute
,例如
onCreate: (db, version) async
await db.execute("CREATE TABLE notes(id TEXT PRIMARY KEY, value TEXT)");
await db.execute("INSERT INTO notes (id, value) VALUES ('home', 'asd')");
await db.execute("INSERT INTO notes (id, value) VALUES ('home2', 'asddf')");
,
DBHelper
class DBHelper
Database _db;
Future<Database> get db async
if (_db != null)
return _db;
_db = await initDatabase();
return _db;
initDatabase() async
return await openDatabase(join(await getDatabasesPath(), "database.db"),
onCreate: (db, version) async
await db.execute("CREATE TABLE notes(id TEXT PRIMARY KEY, value TEXT)");
await db.execute("INSERT INTO notes (id, value) VALUES ('home', 'asd')");
await db.execute("INSERT INTO notes (id, value) VALUES ('home2', 'asddf')");
,
version: 1);
Future<void> updateNote(DBNoteModel dbnoteupdate) async
_db.update("notes", dbnoteupdate.toMap(), where: 'id = ?', whereArgs: [dbnoteupdate.id]);
Future<void> insertNote(DBNoteModel dbnoteupdate) async
_db.insert("notes", dbnoteupdate.toMap());
Future<List<DBNoteModel>> selectNote(String value) async
_db = await db;
List<Map> result;
if(value == "")
result = await _db.query("notes");
else
result = await _db.query("notes", where: "value LIKE '" + value + "%'");
List<DBNoteModel> r_DBNoteModel = result.map((i) => DBNoteModel.fromMap(i)).toList();
return r_DBNoteModel;
在ListView中显示一些数据,在选项卡=>更新,在文本字段更改=>选择Like?*,在FloatingButton =>插入
class sqFliteSimpleExample extends StatefulWidget
@override
_sqFliteSimpleExampleState createState() => _sqFliteSimpleExampleState();
class _sqFliteSimpleExampleState extends State<sqFliteSimpleExample>
List<DBNoteModel> dbnotes = new List();
final DBHelper _dbHelper = DBHelper();
TextEditingController editingController = new TextEditingController();
@override
void initState()
//fetch Notes for the firstTime
getNotes("");
super.initState();
getNotes(String where)
// Select with a where or without
_dbHelper.selectNote(where).then((value)
// return value is a List<DBNoteModel>
setState(()
// refresh screen with the new values
dbnotes = value;
);
);
@override
Widget build(BuildContext context)
return new Scaffold(
appBar: new AppBar(title: new Text("SqFilte Notes"),),
body: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Expanded(
child: new ListView.builder(
itemCount: dbnotes.length,
itemBuilder: (BuildContext context, index)
return new ListTile(
title: Text(dbnotes[index].id.toString()),
subtitle: Text(dbnotes[index].value),
onTap: ()
// updates you local Datamodel
dbnotes[index].value = dbnotes[index].value + " update";
// send sql Update
_dbHelper.updateNote(dbnoteupdate: dbnotes[index]).then((value)
// refresh when it's done
getNotes("");
);
,
);
,
),
),
new Padding(
padding: const EdgeInsets.all(15.0),
child: new TextField(
controller: editingController,
onChanged: (value) => getNotes(value), // refresh the screen every string input in the TextField
decoration: InputDecoration(
hintText: 'search / create',
border: InputBorder.none,
),
),
),
],
),
floatingActionButton: new FloatingActionButton(
child: Icon(Icons.add),
onPressed: ()
//insert a new Note, and refresh when it's done
_dbHelper.insertNote(dbnoteupdate: new DBNoteModel(id: editingController.text, value: editingController.text)).then((value)
getNotes("");
);
),
);
以上是关于Flutter:如何使用SQFlite存储的数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何在flutter中将图像数据保存到sqflite数据库以进行持久化