Flutter之数据存储

偏好存储

shared_preferences 类比iOS中的UserDefaults,使用方法比较简单。 地址戳这里 pub get之后会自动出现一个这样的文件generated_plugin_registrant.dart

image.png 数据存储:

void _incrementCounter() {
  //创建对象,用于操作存储和读取。
  SharedPreferences.getInstance().then((SharedPreferences prefs) {
    setState(() {
      _counter++;
    });
    prefs.setInt('counter', _counter);
  });
  }
复制代码

数据读取:

 SharedPreferences.getInstance().then((SharedPreferences prefs) {
      setState(() {
        _counter = prefs.getInt('counter') ?? 0;
      });
    });
复制代码

sqlite

使用sqlite(链接)需要搭配着path(链接)一起使用,在使用的过程中踩了一个坑, 明明我安装了CocoaPods却一直提示我CocoaPods not installed

Warning: CocoaPods not installed. Skipping pod install. 
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code 
that responds to your plugin usage on the Dart side. 
Without CocoaPods, plugins will not work on iOS or macOS. 
For more info, see https://flutter.dev/platform-plugins To install 
see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.
复制代码

最后解决办法 1;打开终端 2; 输入open /Applications/Android\ Studio.app即可。感觉挺奇怪的一个错误 感谢大佬,问题解决链接

创建表

1.getDatabasesPath来到了Documents下的目录 2.join(value, 'test_db.db')使用的是一个path的pub库配合使用 3.openDatabase打开数据库,onCreate建表 // 建表 CREATE TABLE 表名(,,)

 late Database _db;

  @override
  void initState() {
    super.initState();
    _initDatabase().then((value) => _db = value);
  }

  Future<Database> _initDatabase() async {
    Database db = await getDatabasesPath()
        .then((value) => join(value, 'test_db.db'))
        .then((value) => openDatabase(value, version: 1,
                onCreate: (Database db, int version) async {
              // 建表
              await db.execute(
                  'CREATE TABLE LK_Text(id INTEGER PRIMARY KEY,name TEXT, age INT)');
            }));
    return db;
  }
复制代码

Future<String> getDatabasesPath() => databaseFactory.getDatabasesPath();是一个Future所以需要async配合着await来使用。 执行之后发现已经创建成功了,大小8kb, 是一个空表。

image.png

数据插入

_db插入数据可以使用事务处理

// 添加数据 INSERT INTO 表名 VALUES (值1,值2,...)

    _db.transaction((txn) async {
      txn
          .rawInsert('INSERT INTO LK_Text(name,age) VALUES("zhangsan",16)')
          .then((value) => print(value));
      txn
          .rawInsert('INSERT INTO LK_Text(name,age) VALUES("lisi",17)')
          .then((value) => print(value));
    });
复制代码

数据查询

// 数据查询 SELECT 列名称 FROM 表名称 *通配符

_db.rawQuery('SELECT * FROM LK_Text').then((value) => print(value));
复制代码

image.png

数据修改

// 修改数据 UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值

_db.rawUpdate('UPDATE LK_TEXT SET age = 18 WHERE age = 16');
复制代码

image.png

删除表

1._db.delete删除表 2._db.close()关闭数据库

  _db
        .rawQuery('SELECT * FROM LK_Text')
        .then((value) => print(value))
        .then((value) {
      // 删除表
      _db.delete('LK_Text').then((value) => _db.close());
    });
复制代码

切记:由于这里是异步的操作,注意执行的顺序!! 校验的话还是很简单,再次写入数据的时候会报错。

image.png

删除数据库

    // 删除数据库
    getDatabasesPath()
        .then((value) => join(value, 'test_db.db'))
        .then((value) => deleteDatabase(value));
复制代码

整体来说还是比较简单的,主要是把sqlite语句写正确。

猜你喜欢

转载自juejin.im/post/7096383768096669710