【Flutter 实战】大量复杂数据持久化

移动开发 作者: 2024-08-24 20:30:01
老孟导读:上一篇文章讲解了 Android 和 iOS 的文件目录系统,此篇文章讲解如何使用 SQLite 保存数据。 欢迎大家投稿:http://laomengit.com/plan/Contrib

添加依赖

dependencies:
  sqflite: ^1.3.1
  path_provider: ^1.6.11
flutter pub get

单例模式创建 SQLite 访问

class DBProvider{

  static final DBProvider _singleton = DBProvider._internal();

  factory DBProvider() {
    return _singleton;
  }

  DBProvider._internal();
}

初始化数据库

import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class DBProvider {
  static final DBProvider _singleton = DBProvider._internal();

  factory DBProvider() {
    return _singleton;
  }

  DBProvider._internal();

  static Database _db;

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await _initDB();
    return _db;
  }

  Future<Database> _initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path,'dbName');
    return await openDatabase(path,version: 1,onCreate: _onCreate,onUpgrade: _onUpgrade);
  }

  ///
  /// 创建Table
  ///
  Future _onCreate(Database db,int version) async {}

  ///
  /// 更新Table
  ///
  Future _onUpgrade(Database db,int oldVersion,int newVersion) async {}
}
///
/// 创建Table
///
Future _onCreate(Database db,int version) async {
  return await db.execute("CREATE TABLE User ("
      "id integer primary key AUTOINCREMENT,"
      "name TEXT,"
      "age TEXT,"
      "sex integer"
      ")");
}

保存数据

class User {
  int id;
  String name;
  int age;
  int sex;

  User({this.id,this.name,this.age,this.sex});

  User.fromJson(Map<String,dynamic> json) {
    id = json['id'];
    name = json['name'];
    age = json['age'];
    sex = json['sex'];
  }

  Map<String,dynamic> toJson() {
    final Map<String,dynamic> data = new Map<String,dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['age'] = this.age;
    data['sex'] = this.sex;
    return data;
  }
}
Future saveData(User user) async {
  var _db = await db;
  return await _db.insert('User',user.toJson());
}
class _AddUser extends StatefulWidget {
  @override
  __AddUserState createState() => __AddUserState();
}

class __AddUserState extends State<_AddUser> {
  String _radioGroupValue = '0';
  TextEditingController _nameController;
  TextEditingController _ageController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _ageController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('保存数据'),),body: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Text('姓名:'),Flexible(
                child: TextField(
                  controller: _nameController,],Row(
            children: <Widget>[
              Text('年龄:'),Flexible(
                child: TextField(
                  controller: _ageController,Row(
            children: <Widget>[
              Text('性别:'),Flexible(
                child: RadioListTile(
                  title: Text('男'),value: '0',groupValue: _radioGroupValue,onChanged: (value) {
                    setState(() {
                      _radioGroupValue = value;
                    });
                  },Flexible(
                child: RadioListTile(
                  title: Text('女'),value: '1',Builder(
            builder: (context) {
              return RaisedButton(
                child: Text('保存'),onPressed: () async {
                  var user = User(
                      name: '${_nameController.text}',age: int.parse('${_ageController.text}'),sex: int.parse('$_radioGroupValue'));

                  int result = await DBProvider().saveData(user);
                  if (result > 0) {
                    Scaffold.of(context).showSnackBar(SnackBar(
                      content: Text('保存数据成功,result:$result'),));
                  } else {
                    Scaffold.of(context).showSnackBar(SnackBar(
                      content: Text('保存数据失败,result:$result'),));
                  }
                },);
            },)
        ],);
  }
}
Future rawInsert(User user) async {
  var _db = await db;
  return await _db.rawInsert(
      'INSERT Into User (name,age,sex) VALUES (?,?,?)',[user.name,user.age,user.sex]);
}

查询数据

Future<List<User>> findAll() async {
    var _db = await db;
    List<Map<String,dynamic>> result = await _db.query('User');

    return result.isNotEmpty ? result.map((e) {
      return User.fromJson(e);
    }).toList():[];
  }
class DatabaseDemo extends StatefulWidget {
  @override
  _DatabaseDemoState createState() => _DatabaseDemoState();
}

class _DatabaseDemoState extends State<DatabaseDemo> {
  List<User> _list = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  _loadData() async {
    _list = await DBProvider().findAll();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sqlite Demo'),body: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              RaisedButton(
                child: Text('查询数据'),onPressed: (){
                  _loadData();
                },RaisedButton(
                child: Text('添加数据'),onPressed: (){
                  Navigator.of(context).push(MaterialPageRoute(builder: (context){
                    return _AddUser();
                  }));
                },Table(
            children: [
              TableRow(children: [
                TableCell(child: Text('id')),TableCell(child: Text('姓名')),TableCell(child: Text('年龄')),TableCell(child: Text('性别')),]),..._list.map((user) {
                return TableRow(children: [
                  TableCell(child: Text('${user.id}')),TableCell(child: Text('${user.name}')),TableCell(child: Text('${user.age}')),TableCell(child: Text(user.sex == 0 ? '男' : '女')),]);
              }).toList()
            ],);
  }
}
Future<List<User>> find(int age) async {
    var _db = await db;
    List<Map<String,dynamic>> result =
        await _db.query('User',where: 'age = ?',whereArgs: [age]);

    return result.isNotEmpty ? result.map((e) {
      return User.fromJson(e);
    }).toList():[];
  }
_loadData() async {
  _list = await DBProvider().find(12);
  setState(() {});
}

更新数据

Future<int> update(User user) async {
  var _db = await db;
  return await _db
      .update('User',user.toJson(),where: 'id = ?',whereArgs: [user.id]);
}
RaisedButton(
  child: Text('修改第一行数据'),onPressed: () {
    if (_list.length > 1) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (context) {
        return _AddUser(
          user: _list[0],);
      }));
    }
  },
RaisedButton(
  child: Text('保存'),onPressed: () async {
    var user = User(
        name: '${_nameController.text}',sex: int.parse('$_radioGroupValue'));
    if (widget.user == null) {
      _saveData(context,user);
    } else {
      _updateData(context,user);
    }
  },)

_updateData(BuildContext context,User user) async {
    user.id = widget.user.id;
    int result = await DBProvider().update(user);
    if (result > 0) {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text('修改数据成功,result:$result'),));
    } else {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text('修改数据失败,result:$result'),));
    }
  }

删除数据

Future<int> delete(int id) async {
  var _db = await db;
  return await _db.delete('User',whereArgs: [id]);
}
RaisedButton(
  child: Text('删除第一行数据'),onPressed: () async {
    if (_list.length > 0) {
      await DBProvider().delete(_list[0].id);
      _loadData();
    }
  },
Future<int> deleteAll() async {
  var _db = await db;
  return await _db.delete('User');
}

总结

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68010.html