Flutter开发(二十二):Flutter本地数据存储

1.shared_perferences 简单介绍

2.shared_perferences 简单使用

3.shared_perferences 简单 demo

shared_perferences 这个并不陌生,Android 也用到这个存储方式。

1.shared_perferences 简单介绍

它是一个简单异步存储插件,使用 key-value 来存储。

2.shared_perferences 简单使用

添加依赖,然后点击 Pub get:

 shared_preferences: ^2.0.8

导入包:

import 'package:shared_preferences/shared_preferences.dart';

存储:

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key, value)
prefs.setBool(key, value)
prefs.setDouble(key, value)
prefs.setInt(key, value)
prefs.setStringList(key, value)

读取:

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.getInt(key); //删除指定键

删除:

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键
prefs.clear();//清空键值对

3.shared_perferences 简单 demo

我以为很简单,没想到报错了:

E/flutter (11319): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)

版本高的要在 main 加 :SharedPreferences.setMockInitialValues({});

demo就是存一下,然后取一下,完整代码如下:

import 'package:shared_preferences/shared_preferences.dart';

void main() {
  SharedPreferences.setMockInitialValues({});
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  late String phone = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Tabbed AppBar'),
        ),
        body: Center(
          child: Column(
            children: [
              RaisedButton(
                onPressed: _add,
                child: Text('存储'),
              ),
              RaisedButton(
                onPressed: _get,
                child: Text('获取'),
              ),
              Text('存储的内容为:' + phone),
            ],
          ),
        ),
      ),
    );
  }

  _add() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString("name", "老王");
  }

  _get() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      phone = prefs.getString("name").toString();
    });
  }
}

你可能感兴趣的:(flutter开发,flutter,android,java)