Flutter数据共享插件shared_store的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter数据共享插件shared_store的使用

shared_store 是一个基于 MMKV 的原生存储解决方案。它为 Flutter 提供了高效的数据存储功能。

示例

iOS

Android

使用方法

一、Flutter端

1. 添加依赖

pubspec.yaml 文件中添加 shared_store 依赖:

dependencies:
  flutter:
    sdk: flutter

  shared_store: ^0.01

然后运行以下命令以安装依赖:

flutter pub get

2. 初始化 SharedStore

在使用 SharedStore 前,需要导入 shared_store_plugin.dart 并调用 initMMKV() 方法进行初始化:

import 'package:shared_store/shared_store_plugin.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late String result = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化 SharedStore
    SharedStorePlugin.initMMKV();
  }
}

3. 添加自定义 MMKV 实例

如果需要添加除默认 default MMKV 外的其他 MMKV 实例,可以使用 addMMKV() 方法:

void addCustomMMKV() {
  String customMMKVId = "testPlugin";
  SharedStorePlugin.addMMKV(customMMKVId);
  setState(() {
    result = "MMKV $customMMKVId add success";
  });
}

4. 存储数据

在需要存储数据时,可以使用以下方法:

void storeTestData() async {
  const bool testBool = true;
  const int testInt = 123456;
  const double testDouble = 3.1415926;
  const String testString = 'testStringValue';

  // 存储布尔值
  String? boolResult = await SharedStorePlugin.storeBool('testBool', testBool);
  // 存储双精度浮点数
  String? doubleResult = await SharedStorePlugin.storeDouble('testDouble', testDouble);
  // 存储整数值
  String? intResult = await SharedStorePlugin.storeInt('testInt', testInt);
  // 存储字符串
  String? stringResult = await SharedStorePlugin.storeString('testString', testString);

  setState(() {
    if (boolResult == 'true' && doubleResult == 'true' && intResult == 'true' && stringResult == 'true') {
      result = 'store value : \n boolValue: $testBool \n intValue: $testInt \n doubleValue: $testDouble \n stringValue: $testString \n store value success';
    } else {
      result = 'store value failed';
    }
  });
}

5. 读取数据

在需要读取数据时,可以使用以下方法:

void readTestData() async {
  bool? readBool = await SharedStorePlugin.readBool('testBool');
  int? readInt = await SharedStorePlugin.readInt('testInt');
  double? readDouble = await SharedStorePlugin.readDouble('testDouble');
  String? readString = await SharedStorePlugin.readString('testString');

  setState(() {
    result = 'read value : \n boolValue: $readBool \n intValue: $readInt \n doubleValue: $readDouble \n stringValue: $readString \n read value success';
  });
}

示例代码

以下是完整的示例代码,展示了如何使用 shared_store 插件:

import 'package:flutter/material.dart';
import 'package:shared_store/shared_store_plugin.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late String result = '';

  void initMMKV() {
    SharedStorePlugin.initMMKV();
    setState(() {
      result = 'init success';
    });
  }

  void addMMKV() {
    String customMMKVId = "testPlugin";
    SharedStorePlugin.addMMKV(customMMKVId);
    setState(() {
      result = "MMKV $customMMKVId add success";
    });
  }

  void storeTestData() async {
    const bool testBool = true;
    const int testInt = 123456;
    const double testDouble = 3.1415926;
    const String testString = 'testStringValue';
    String? boolResult = await SharedStorePlugin.storeBool('testBool', testBool);
    String? doubleResult = await SharedStorePlugin.storeDouble('testDouble', testDouble);
    String? intResult = await SharedStorePlugin.storeInt('testInt', testInt);
    String? stringResult = await SharedStorePlugin.storeString('testString', testString);

    setState(() {
      if (boolResult == 'true' && doubleResult == 'true' && intResult == 'true' && stringResult == 'true') {
        result = 'store value : \n boolValue: $testBool \n intValue: $testInt \n doubleValue: $testDouble \n stringValue: $testString \n store value success';
      } else {
        result = 'store value failed';
      }
    });
  }

  void readTestData() async {
    bool? readBool = await SharedStorePlugin.readBool('testBool');
    int? readInt = await SharedStorePlugin.readInt('testInt');
    double? readDouble = await SharedStorePlugin.readDouble('testDouble');
    String? readString = await SharedStorePlugin.readString('testString');

    setState(() {
      result = 'read value : \n boolValue: $readBool \n intValue: $readInt \n doubleValue: $readDouble \n stringValue: $readString \n read value success';
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('SharedStore example app'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              Row(
                children: [
                  CustomButton(
                      title: '1,initMMKV',
                      onTap: () {
                        initMMKV();
                      }),
                  Expanded(
                    child: Container(),
                  ),
                  CustomButton(
                      title: '2,addMMKV',
                      onTap: () {
                        addMMKV();
                      })
                ],
              ),
              const Divider(
                height: 40,
                color: Colors.white,
              ),
              Row(
                children: [
                  CustomButton(
                      title: '3,setData',
                      onTap: () {
                        storeTestData();
                      }),
                  Expanded(child: Container()),
                  CustomButton(
                      title: '4,getData',
                      onTap: () {
                        readTestData();
                      })
                ],
              ),
              const Divider(
                height: 20,
                color: Colors.white,
              ),
              ConsolePage(consoleText: result),
            ],
          ),
        ),
      ),
    );
  }
}

class CustomButton extends StatelessWidget {
  const CustomButton({Key? key, required this.title, required this.onTap}) : super(key: key);
  final String title;
  final void Function() onTap;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.black, width: 0.5),
            borderRadius: const BorderRadius.all(Radius.circular(5)),
            boxShadow: const [
              BoxShadow(color: Colors.black, offset: Offset(3.0, 3.0), blurRadius: 5.0, spreadRadius: 1.0),
              BoxShadow(color: Colors.grey, offset: Offset(-3.0, -3.0), blurRadius: 5.0, spreadRadius: 1.0)
            ]),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(child: Text(title)),
        ),
      ),
    );
  }
}

class ConsolePage extends StatelessWidget {
  const ConsolePage({Key? key, this.consoleText = ""}) : super(key: key);
  final String consoleText;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey,
        border: Border.all(color: Colors.black, width: 0.5),
        borderRadius: const BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.all(5),
            child: Text('console:'),
          ),
          Padding(padding: const EdgeInsets.all(10), child: Text(consoleText)),
        ],
      ),
    );
  }
}

更多关于Flutter数据共享插件shared_store的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据共享插件shared_store的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


shared_store 是一个用于在 Flutter 应用中实现数据共享的插件。它允许你在不同的页面或组件之间共享数据,而不需要手动传递数据或使用全局变量。shared_store 通常用于存储和访问应用中的共享状态,例如用户信息、设置、缓存数据等。

安装 shared_store

首先,你需要在 pubspec.yaml 文件中添加 shared_store 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  shared_store: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

使用 shared_store

1. 初始化 SharedStore

在使用 shared_store 之前,你需要在应用的入口处初始化它。通常,你可以在 main.dart 文件中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SharedStore.init();  // 初始化 SharedStore
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

2. 存储数据

你可以使用 SharedStore 来存储数据。例如,存储一个字符串:

SharedStore.setString('key', 'value');

你也可以存储其他类型的数据,如 intdoubleboolListMap 等:

SharedStore.setInt('intKey', 42);
SharedStore.setDouble('doubleKey', 3.14);
SharedStore.setBool('boolKey', true);
SharedStore.setList('listKey', [1, 2, 3]);
SharedStore.setMap('mapKey', {'name': 'John', 'age': 30});

3. 读取数据

你可以使用 SharedStore 来读取之前存储的数据:

String value = SharedStore.getString('key');
int intValue = SharedStore.getInt('intKey');
double doubleValue = SharedStore.getDouble('doubleKey');
bool boolValue = SharedStore.getBool('boolKey');
List<dynamic> listValue = SharedStore.getList('listKey');
Map<dynamic, dynamic> mapValue = SharedStore.getMap('mapKey');

如果键不存在,SharedStore 会返回 null

4. 删除数据

你可以使用 SharedStore 来删除存储的数据:

SharedStore.remove('key');

5. 清除所有数据

你可以使用 SharedStore 来清除所有存储的数据:

SharedStore.clear();

示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 shared_store 来存储和读取数据:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SharedStore.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _storedValue = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    _loadStoredValue();
  }

  void _loadStoredValue() async {
    String value = SharedStore.getString('key') ?? 'No value stored';
    setState(() {
      _storedValue = value;
    });
  }

  void _storeValue() async {
    await SharedStore.setString('key', 'Hello, SharedStore!');
    _loadStoredValue();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SharedStore Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Stored Value:',
            ),
            Text(
              _storedValue,
              style: Theme.of(context).textTheme.headline4,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _storeValue,
              child: Text('Store Value'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!