flutter 数据存储 SP和sqlite

添加插件:

  shared_preferences: ^0.4.2
  path_provider: ^1.2.0
  sqflite: ^0.12.0
import ‘dart:async‘;
import ‘dart:io‘;

import ‘package:flutter/material.dart‘;
import ‘package:path/path.dart‘;
import ‘package:path_provider/path_provider.dart‘;
import ‘package:shared_preferences/shared_preferences.dart‘;
import ‘package:sqflite/sqflite.dart‘;

String username = ‘‘;

String pwd = ‘‘;

const String USERNAME = ‘username‘;

const String PWD = ‘pwd‘;

class DataAppPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _DataAppPageState();
  }
}

class _DataAppPageState extends State<DataAppPage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(‘数据存储 学习‘),
        centerTitle: true,
      ),
      body: new ListView(
        children: <Widget>[
          new Padding(
            padding: const EdgeInsets.only(left: 10.0, top: 10.0, right: 10.0),
            child: new Text(‘对用户名和密码进行增删改查的操作‘),
          ),
          new Padding(
            padding: const EdgeInsets.only(left: 10.0, right: 10.0),
            child: new LoginWidget(),
          ),
          new Padding(
            padding: const EdgeInsets.only(
                top: 10.0, left: 10.0, bottom: 10.0, right: 10.0),
            child: new HandleSPDataWidget(),
          ),
          new Padding(
            padding: const EdgeInsets.only(
                top: 10.0, left: 10.0, bottom: 10.0, right: 10.0),
            child: new HandleSQLiteDataWidget(),
          ),
          new Padding(
            padding: const EdgeInsets.only(
                top: 10.0, left: 10.0, bottom: 10.0, right: 10.0),
            child: new HandleFileDataWidget(),
          ),
        ],
      ),
    );
  }
}

class HandleSPDataWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _HandleSPDataWidgetState();
  }
}

class _HandleSPDataWidgetState extends State<HandleSPDataWidget> {
  var _result;

  _add() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString(USERNAME, username);

    prefs.setString(PWD, pwd);

    setState(() {
      _result = ‘_add 成功 请点击查验证结果‘;
    });
  }

  _delete() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    //KEY
    prefs.remove(USERNAME);
    prefs.remove(PWD);

    //清空所有KEY
    //prefs.clear();

    setState(() {
      _result = ‘_delete 成功, 请点击查验证结果‘;
    });
  }

  _update() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString(USERNAME, ‘Paul‘);

    prefs.setString(PWD, ‘654321‘);

    setState(() {
      _result = ‘_update 成功,用户名修改为Paul,密码修改为654321, 请点击查验证结果‘;
    });
  }

  _query() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    String username = prefs.get(USERNAME);

    String pwd = prefs.get(PWD);

    print(‘$username‘);

    print(‘$pwd‘);

    setState(() {
      _result = ‘_query 成功: username: $username pwd: $pwd‘;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return new Column(
      children: <Widget>[
        new Padding(
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          child: new Text(‘shared_preferences用法‘),
        ),

        new Row(
          children: <Widget>[
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘增‘),
                onPressed: _add
            ),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘删‘),
                onPressed: _delete),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘改‘),
                onPressed: _update),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘查‘),
                onPressed: _query),
          ],),
        new Padding(
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          child: new Text(‘结果:$_result‘),
        ),
      ],
    );
  }
}

class HandleSQLiteDataWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _HandleSQLiteDataWidgetState();
  }
}

class _HandleSQLiteDataWidgetState extends State<HandleSQLiteDataWidget> {
  // TODO: implement build

  String dbName = ‘user.db‘;
  String dbPath;

  String sql_createTable =
      ‘CREATE TABLE user_table (id INTEGER PRIMARY KEY, username TEXT,pwd Text)‘;

  String sql_query_count = ‘SELECT COUNT(*) FROM user_table‘;

  String sql_query = ‘SELECT * FROM user_table‘;

  var _result;

  Future<String> _createNewDb(String dbName) async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    print(documentsDirectory);

    String path = join(documentsDirectory.path, dbName);

    if (await new Directory(dirname(path)).exists()) {
      await deleteDatabase(path);
    } else {
      try {
        await new Directory(dirname(path)).create(recursive: true);
      } catch (e) {
        print(e);
      }
    }
    return path;
  }

  _create() async {
    dbPath = await _createNewDb(dbName);
    Database db = await openDatabase(dbPath);

    await db.execute(sql_createTable);
    await db.close();
    setState(() {
      _result = ‘创建user.db成功,创建user_table成功‘;
    });
  }

  _add() async {

    Database db = await openDatabase(dbPath);

    String sql =
        "INSERT INTO user_table(username,pwd) VALUES(‘$username‘,‘$pwd‘)";
    await db.transaction((txn) async {
      int id = await txn.rawInsert(sql);
    });

    await db.close();

    setState(() {
      _result = "插入username=$username,pwd=$pwd数据成功";
    });
  }

  _delete() async {
    Database db = await openDatabase(dbPath);

    String sql = "DELETE FROM user_table WHERE id = ?";

    int count = await db.rawDelete(sql, [‘1‘]);

    await db.close();

    setState(() {
      if (count == 1) {
        _result = "删除成功,请查看";
      } else {
        _result = "删除失败,请看log";
      }
    });
  }

  _update() async {
    Database db = await openDatabase(dbPath);
    String sql = "UPDATE user_table SET pwd = ? WHERE id = ?";
    int count = await db.rawUpdate(sql, ["654321", ‘1‘]);
    print(count);
    await db.close();
    setState(() {
      _result = "更新数据成功,请查看";
    });
  }

  _queryNum() async {
    Database db = await openDatabase(dbPath);
    int count = Sqflite.firstIntValue(await db.rawQuery(sql_query_count));
    await db.close();
    setState(() {
      _result = "数据条数:$count";
    });
  }

  _query() async {
    Database db = await openDatabase(dbPath);
    List<Map> list = await db.rawQuery(sql_query);
    await db.close();
    setState(() {
      _result = "数据详情:$list";
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new Padding(
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          child: new Text(‘sqflite用法‘),
        ),
        new Row(
          children: <Widget>[
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘创建‘),
                onPressed: _create),
            new RaisedButton(
                textColor: Colors.black, child: new Text(‘增‘), onPressed: _add),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘删‘),
                onPressed: _delete),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘改‘),
                onPressed: _update),
          ],
        ),
        new Row(
          children: <Widget>[
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘查条数‘),
                onPressed: _queryNum),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘查详情‘),
                onPressed: _query),
          ],
        ),
        new Padding(
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          child: new Text(‘结果:$_result‘),
        ),
      ],
    );
  }
}

class HandleFileDataWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _HandleFileDataWidgetState();
  }
}

class _HandleFileDataWidgetState extends State<HandleFileDataWidget> {
  // TODO: implement build

  String tempPath;

  String appDocPath;

  String sdCardPath;

  var _result;

  _add() async {

    File file = new File(‘$tempPath/user.txt‘);
    await file.writeAsString(‘用户名:$username\n密码:$pwd‘);
    setState(() {
      _result = ‘写入成功,请查询‘;
    });
  }

  _delete() {
    File file = new File(‘$tempPath/user.txt‘);
    file.deleteSync(recursive: false);
    setState(() {
      _result = ‘删除成功,请查看‘;
    });
  }

  _update() async {
    File file = new File(‘$tempPath/user.txt‘);
    await file.writeAsString(‘用户名:Paul\n密码:654321‘);
    setState(() {
      _result = ‘修改成功,请查询‘;
    });
  }

  _query() async {
    try {
      File file = new File(‘$tempPath/user.txt‘);
      _result = ‘查询成功\n‘ + await file.readAsString();
    } on Exception catch (e) {
      _result = ‘ exception: $e‘;
    }

    setState(() {});
  }

  void _requestTempDirectory() async {
    Directory tempDir = await getTemporaryDirectory();
    setState(() {
      tempPath = tempDir.path;
    });
  }

  void _requestAppDocumentsDirectory() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    setState(() {
      appDocPath = appDocDir.path;
    });
  }

  void _requestExternalStorageDirectory() async {
    Directory sdCardDir = await getExternalStorageDirectory();
    setState(() {
      sdCardPath = sdCardDir.path;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _requestTempDirectory();

    _requestAppDocumentsDirectory();

    _requestExternalStorageDirectory();
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new Padding(
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          child: new Text(‘文件用法‘),
        ),
        new Row(
          children: <Widget>[
            new RaisedButton(
                textColor: Colors.black, child: new Text(‘增‘), onPressed: _add),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘删‘),
                onPressed: _delete),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘改‘),
                onPressed: _update),
            new RaisedButton(
                textColor: Colors.black,
                child: new Text(‘查‘),
                onPressed: _query),
          ],
        ),
        new Padding(
          padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          child: new Text(‘结果:$_result‘),
        ),
        new Text(‘缓存文件路径:‘),
        new Padding(
          padding: const EdgeInsets.only(bottom: 10.0),
          child: new Text(‘$tempPath‘),
        ),
        new Text(‘应用文件路径:‘),
        new Padding(
          padding: const EdgeInsets.only(bottom: 10.0),
          child: new Text(‘$appDocPath‘),
        ),
        new Text(‘Android SD卡路径:‘),
        new Padding(
          padding: const EdgeInsets.only(bottom: 10.0),
          child: new Text(‘$sdCardPath‘),
        ),
      ],
    );
  }
}

class LoginWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var node = new FocusNode();
    return new Column(
      children: <Widget>[
        new TextField(
          onChanged: (str) {
            username = str;
            print(username);
          },
          decoration: new InputDecoration(
            labelText: ‘用户名‘,
            hintText: ‘请输入英文或数字‘,
          ),
          maxLines: 1,
          onSubmitted: (text) {
            FocusScope.of(context).requestFocus(node);
          },
        ),
        new TextField(
          onChanged: (text) {
            pwd = text;
            print(pwd);
          },
          obscureText: true,
          maxLines: 1,
          decoration:
              new InputDecoration(hintText: ‘请输入长度大于6的密码‘, labelText: ‘密码‘),
          keyboardType: TextInputType.text,
          onSubmitted: (text) {},
        ),
      ],
    );
  }
}

class DataPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      body: new DataAppPage(),
    );
  }
}

效果:

原文地址:https://www.cnblogs.com/loaderman/p/11352516.html

时间: 2024-11-19 03:00:31

flutter 数据存储 SP和sqlite的相关文章

Flutter 数据存储之 shared_preferences

资源名称 网址 github https://github.com/flutter/plugins/tree/master/packages/shared_preferences Flutter 数据存储之 shared_preferences https://juejin.im/post/5bab0e06f265da0a972e2417 原文地址:https://www.cnblogs.com/cag2050/p/10960376.html

数据存储——SP存储

一.存储方式分类:SharedPreferences存储 二.SharedPreferences存储 1.特点 ①存储单一数据,例如数值,字符串,布尔 ②文件:/date/date/包名/shared_prefs/xxx.xml:    <map><string  name="key">value</string></map> ③以键值对的形式存储 ④可以设置不被其他应用操作 2.API (1)SharedPreferences ①获取实

Android开发(二十四)——数据存储SharePreference、SQLite、File、ContentProvider

Android提供以下四种存储方式: SharePreference SQLite File ContentProvider Android系统中数据基本都是私有的,一般存放在“data/data/程序包名”目录下.如果要实现数据共享,正确的方式是使用ContentProvider. 参考: http://www.cnblogs.com/rond/p/3553156.html http://blog.csdn.net/flowingflying/article/details/6671548%2

android 数据存储操作之SQLite

一. SQLite介绍 SQLite是android内置的一个很小的关系型数据库. 二. SQLiteOpenHelper的使用方法 ①SQLiteOpenHelper是一个辅助类来管理数据库的创建和版本.②可以通过继承这个类,实现它的一些方法来对数据库进行一些操作.③所有继承了这个类的类都必须实现下面这样的一个构造方法: public SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory fact

Android数据存储之SQLite的操作

Android作为一个应用在移动设备上的操作系统,自然也就少不了数据的存储.然而SQLite作为一个轻型的关系型数据库,基于其轻量.跨平台.多语言接口及安全性等诸多因数考虑,因而Android较大的数据存储采用了SQLite.SQLite与大多数关系型数据库一样都遵循ACID,语法也非常相似.只要您懂得mysql.sqlserver等关系型数据库的操作,只要查看下SQLite的官方文档便可快速上手.SQLite语法您可通过http://sqlite.org/lang.html进行查看. 接下来看

Android简易数据存储之SharedPreferences

Andorid提供了多种数据存储的方式,例如前面说到的“Android数据存储之SQLite的操作”是用于较复杂的数据存储.然而,如果有些简单的数据存储如果采用SQLite的方式的话会显得比较笨重.例如:记录用户是否访问过APP的欢迎页面之类的数据,如果采用SQLite的话会显得没必要而且费时费力.因此Andorid提供了另一种存储简单数据的方式SharedPreferences.SharedPreferences是一个轻量级的数据存储方式,其仅支持boolean.int.long.float.

无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)

1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.example.demo1" /> 上面targetPackage指定的包要和应用的package相同. (2)在清单文件中ap

Android学习笔记 --- 数据存储与访问 (File,sdcard,sharedpreferences,sqlite)

一.使用文件进行数据存储 1.context.openFileOutput()方法  写入文件内容 在上下文context中 openFileOutput方法可以用于把数据输出到文件中 示例代码: public static void fileStorage(Context context){ try { FileOutputStream fos = context.openFileOutput("filedata.txt", context.MODE_PRIVATE); fos.wr

安卓数据存储(3):SQLite数据库存储

SQLite简介 Google为Andriod的较大的数据处理提供了SQLite,他在数据存储.管理.维护等各方面都相当出色,功能也非常的强大.SQLite具备下列特点: 1.轻量级:使用 SQLite 只需要带一个动态库,就可以享受它的全部功能,而且那个动态库的尺寸想当小. 2.独立性:SQLite 数据库的核心引擎不需要依赖第三方软件,也不需要所谓的“安装”. 3.隔离性:SQLite 数据库中所有的信息(比如表.视图.触发器等)都包含在一个文件夹内,方便管理和维护. 4.跨平台:SQLit