关于python:Flutter的三种本地存储方式-文件SharedPreferences数据库

3次阅读

共计 5482 个字符,预计需要花费 14 分钟才能阅读完成。

SharedPreferences 存储

缓存大量的键值对信息(比方记录用户是否浏览了布告,或是简略的计数),能够应用 SharedPreferences。

SharedPreferences 会以原生平台相干的机制,为简略的键值对数据提供长久化存储,即在 iOS 上应用 NSUserDefaults,在 Android 应用 SharedPreferences。

SharedPreferences 的应用形式非常简单不便。不过须要留神的是,以键值对的形式只能存储根本类型的数据,比方 int、double、bool 和 string。

1. pubspec.yaml 引入

shared_preferences: 0.5.12+4

2. 代码

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue,),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

// 波及到耗时的文件读写,以异步的形式对这些操作进行包装

// 读取 SharedPreferences 中 key 为 counter 的值
  Future<int> _loadCounter() async {SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0);
    return counter;
  }

// 递增写入 SharedPreferences 中 key 为 counter 的值
  Future<void> _incrementCounter() async {SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    print("以后值:" + counter.toString());
    prefs.setInt('counter', counter);  //setter(setInt)办法会同步更新内存中的键值对,而后将数据保留至磁盘,因而无需再调用更新办法强制刷新缓存
  }

  _fresh() {// _incrementCounter();

    _incrementCounter().then((_) => {_loadCounter().then((value) {setState(() {_counter = value;});
            print("before:$value");
          })
        });
  }

  // void _incrementCounter() {//   setState(() {

  //     _counter++;
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:',),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fresh,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

数据库存储

如果须要长久化大量格式化后的数据,并且这些数据还会以较高的频率更新,为了思考进一步的扩展性,通常会选用 sqlite 数据库来应答这样的场景。

与文件和 SharedPreferences 相比,数据库在数据读写上能够提供更快、更灵便的解决方案。

1. pubspec.yaml 引入

  sqflite: 1.3.2+1 
  path_provider: ^1.6.24
    

2. 代码

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

void main() {runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue,),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class Student {
  String id;
  String name;
  int score;
  // 构造方法
  Student({
    this.id,
    this.name,
    this.score,
  });
  // 用于将 JSON 字典转换成类对象的工厂类办法
  factory Student.fromJson(Map<String, dynamic> parsedJson) {
    return Student(id: parsedJson['id'],
      name: parsedJson['name'],
      score: parsedJson['score'],
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'score': score,
    };
  }
}

class _MyHomePageState extends State<MyHomePage> {var student1 = Student(id: '123', name: '张三', score: 110);

  query_database(id) {Future<Student> user = query_by_id(id);
    user.then((t) {print("单用户查问胜利");
      print('the sroce is :' + t.score.toString());
      student1.score = t.score;
    });
  }

  // 插入数据
  Future<void> insertStudent(Student std) async {
    final Database db = await database;
    await db.insert(
      'students',
      std.toJson(),
      // 插入抵触策略,新的替换旧的
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<Student> query_by_id(String id) async {
    final Database db = await database;
    List<Map> maps = await db.query('students',
        columns: ['id', 'name', 'score'], where: 'id = ?', whereArgs: [id]);
    if (maps.length > 0) {print("依据 id 查到了数据");
      return Student.fromJson(maps.first);
    }
    print("依据 id 没有查到数据");
    return null;
  }

  // 初始化数据库办法
  initDB() async {Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "students_database.db");

    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {await db.execute('''CREATE TABLE students(id TEXT PRIMARY KEY, name TEXT, score INTEGER)''');
    });
  }

  Database _database;

  Future<Database> get database async {if (_database != null) {print(_database);
      return _database;
    }

    _database = await initDB();
    print("创立新数据库");
    return _database;
  }

  void _incrementCounter() async {
    student1.score += 1;
    await insertStudent(student1);

    setState(() {});
  }

  Future<List<Student>> students() async {
    final Database db = await database;
    final List<Map<String, dynamic>> maps = await db.query('students');
    return List.generate(maps.length, (i) => Student.fromJson(maps[i]));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:',),
            Text(student1.score.toString(),
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  @override
  void dispose() async {
    // TODO: implement dispose
    super.dispose();
    final Database db = await database;

    db.close();}
}

Flutter 写的 app, 须要源码能够私信~~

  • 简繁火星字体转换
  • 哄女友神器
  • 号码测吉凶
  • 电视节目直播表

最好的笔记软件

正文完
 0