繁体   English   中英

Flutter:如何使用 SQFlite 存储的数据?

[英]Flutter: How to use data stored with SQFlite?

我真的在为 Flutter 和 SQFlite 苦苦挣扎。 周围有很多复杂的示例,但没有一个简单的示例仅用于获取数据并将其放入变量中以用于小部件或 model。 我尝试了一堆示例,其中大多数给出了错误“表不存在”。 我终于找到了一个可行的示例,并尝试将其分叉以满足我的需求,但我迷路了。 我是 flutter 的新手,但不是编码的新手。 多年来一直在做 web 编码。 我已经浪费了几个小时试图让一个简单的查询工作并在一个变量中返回它的内容。 我真的在考虑完全放弃 Flutter 只是因为处理存储数据的难度。 这应该是基本的东西。 怎么弄得这么难??

无论如何,这是我的代码,所以你可以看到我想要实现的目标。 我可以在 DBHelper class 中创建数据库、插入和获取数据,但我不知道如何在它之外使用这些数据。 我的目标是让一个简单的例子工作,然后我可以在我的整个应用程序中更大规模地实现它。 我有不同类型的动态列表等。任何帮助将不胜感激!

数据库.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;
  }
}

测试.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')");
},

数据库助手

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 中显示一些数据,在选项卡上 => 更新,在文本字段更改 => select 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("");
          });
        }
      ),
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM