Flutter本地存储插件hive_local_storage的使用

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

Flutter本地存储插件hive_local_storage的使用

hive_local_storage简介

hive_local_storage 是一个用于在Flutter应用程序中存储用户会话和缓存值的工具包。它利用了Hive进行缓存,并使用flutter_secure_storage来存储加密密钥,以确保会话存储的安全性。

开始使用

添加依赖

pubspec.yaml文件中添加以下依赖:

dependencies:
  hive_local_storage: latest

dev_dependencies:
  build_runner: latest
  hive_generator: latest

导入包

在需要使用的Dart文件顶部导入hive_local_storage

import 'package:hive_local_storage/hive_local_storage.dart';

注册自定义适配器

如果要使用自定义类,请注册相应的适配器。注意:避免为数据类使用typeId=0,因为该ID已被会话类占用。

final localStorage = await LocalStorage.getInstance(registerAdapters:(){
  Hive..registerAdapter(adapter1)..registerAdapter(adapter2);
});

会话管理

存储会话

final storage = await LocalStorage.getInstance();
await storage.saveToken('accessToken','refreshToken'); // refreshToken是可选的

获取会话

final storage = await LocalStorage.getInstance();
final accessToken = storage.accessToken;
final refreshToken = storage.refreshToken;
final bool hasSession = storage.hasSession;

StreamSubscription<bool> _subscription = storage.onSessionChange.listen((bool hasSession){
  // 执行相应操作
});
_subscription.cancel(); // 取消订阅

final isTokenExpired = localStorage.isTokenExpired;

移除会话

final storage = await LocalStorage.getInstance();
storage.clearSession();

自定义盒子

当您想直接存储Hive对象时,可以打开自定义盒子。为此,您需要在初始化时为Hive对象注册适配器。

/// typeId 必须在 1-223 之间
@HiveType(typeId:1,adapterName:'TestAdapter')
class TestModel extends HiveObject{
  @HiveField(0)
  late String firstName;
}

final localStorage = await LocalStorage.getInstance([TestAdapter()]);
await localStorage.openBox<TestModel>(boxName:'__TEST_BOX__',typeId:1)

从自定义盒子读取数据

final localStorage = await LocalStorage.getInstance();
List<TestModel> data = localStorage.values<TestModel>('__TEST_BOX__');

向自定义盒子写入数据

final localStorage = await LocalStorage.getInstance();
void storeData() async {
  final testModel = TestModel();
  await localStorage.add<TestModel>(boxName: '__TEST_BOX__',value:testModel);

  final listData = <TestModel>[TestModel(),TestModel()];
  await localStorage.addAll<TestModel>(boxName: '__TEST_BOX__',values:listData);
}

从自定义盒子删除数据

final localStorage = await LocalStorage.getInstance();
void deleteData(TestModel test) async {
  await localStorage.delete<TestModel>(boxName: '__TEST_BOX__',value:test);
}

更新自定义盒子中的数据

final localStorage = await LocalStorage.getInstance();
void updateData(TestModel test) async {
  await localStorage.update<TestModel>(boxName: '__TEST_BOX__',value:test);
}

使用Riverpod

/// 创建provider
final localStorageProvider = Provider<LocalStorage>((ref)=>throw UnImplementedError());

/// 在main函数中
void main() {
  runZonedGuarded(
    () async {
      final localStorage = await LocalStorage.getInstance();
      runApp(
        ProviderScope(
          overrides: [
            localStorageProvider.overrideWithValue(localStorage),
          ],
          child: App(),
        ),
      );
    },
    (e, _) => throw e,
  );
}

缓存操作

写入缓存

final localStorage = await LocalStorage.getInstance();

// 存储单个值
await localStorage.put<int>(key:'count',value:0);

// 存储多个值
await localStorage.putAll(Map<String, dynamic> entries);

// 存储列表数据
await localStorage.putList<Model>(key:'KeyName',value:<Model>[]);

读取缓存

final localStorage = await LocalStorage.getInstance();

// 获取单个值
final count = localStorage.get<int>(key:'count');

// 监听键值变化
localStorage.watchKey(key:'key').listen((value){
  // 执行相应操作
});

// 读取列表数据
final listData = localStorage.getList<Model>(key:'Your KeyName');

删除缓存

final localStorage = await LocalStorage.getInstance();

// 移除单个值
await localStorage.remove(key:'count');

// 清空所有缓存
await localStorage.clear();

// 清空会话和缓存
await localStorage.clearAll();

示例代码

下面是一个完整的示例代码,展示了如何在Flutter应用中使用hive_local_storage

import 'dart:math';

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

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

  void _incrementCounter() async {
    await _localStorage.put(key: 'counter', value: Random().nextInt(100));
  }

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

  void _init() async {
    _localStorage = await LocalStorage.getInstance();
    _counter = _localStorage.get<int>(key: 'counter', defaultValue: 0)!;

    _localStorage.watchKey<int>(key: 'counter').listen((event) {
      setState(() {
        _counter = event ?? 0;
      });
    });
  }

  void _remove() async {
    await _localStorage.clear();
  }

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

通过以上内容,您可以了解如何在Flutter项目中使用hive_local_storage插件来进行本地存储。希望这些信息对您有所帮助!


更多关于Flutter本地存储插件hive_local_storage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地存储插件hive_local_storage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter应用中使用hive_local_storage插件进行本地存储的示例代码。hive_local_storage是一个高效的键值对存储解决方案,它使用Dart的序列化机制来存储对象。

首先,确保你已经在pubspec.yaml文件中添加了hivehive_flutter_helper依赖:

dependencies:
  flutter:
    sdk: flutter
  hive: ^2.0.4  # 请检查最新版本号
  hive_flutter_helper: ^1.1.0  # 请检查最新版本号

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

接下来,你需要定义一些模型类,这些类需要实现HiveType接口。以下是一个简单的示例:

import 'package:hive/hive.dart';

part 'user.g.dart';

@HiveType(typeId: 0)
class User extends HiveObject {
  @HiveField(0)
  String name;

  @HiveField(1)
  int age;

  User(this.name, this.age);
}

注意:在上面的代码中,part 'user.g.dart'; 是必要的,因为Hive使用代码生成来创建必要的序列化代码。你需要运行flutter pub run build_runner build来生成这些文件。

然后,在你的应用中初始化Hive并打开一个Box来存储你的数据:

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter_helper/hive_flutter_helper.dart';
import 'user.dart';  // 导入你的模型类

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化Hive
  final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
  final hiveBoxPath = appDocumentDirectory.path + '/hive_box';
  Hive.initFlutter(hiveBoxPath);

  // 打开一个Box来存储User对象
  final box = await Hive.openBox<User>('users');

  runApp(MyApp(box));
}

class MyApp extends StatelessWidget {
  final Box<User> box;

  MyApp(this.box);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hive Example'),
        ),
        body: HiveExampleScreen(box),
      ),
    );
  }
}

class HiveExampleScreen extends StatefulWidget {
  final Box<User> box;

  HiveExampleScreen(this.box);

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

class _HiveExampleScreenState extends State<HiveExampleScreen> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _ageController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          TextField(
            controller: _nameController,
            decoration: InputDecoration(labelText: 'Name'),
          ),
          TextField(
            controller: _ageController,
            decoration: InputDecoration(labelText: 'Age'),
            keyboardType: TextInputType.number,
          ),
          ElevatedButton(
            onPressed: () async {
              final name = _nameController.text;
              final age = int.tryParse(_ageController.text) ?? 0;

              if (name.isNotEmpty && age > 0) {
                final user = User(name, age);
                await widget.box.put('user-1', user);

                // 读取并显示存储的用户
                final storedUser = await widget.box.get('user-1');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Stored User: ${storedUser?.name}, ${storedUser?.age}')),
                );
              }
            },
            child: Text('Save User'),
          ),
        ],
      ),
    );
  }
}

在这个示例中,我们定义了一个User类,并使用Hive将其存储在本地。我们在main函数中初始化了Hive并打开了一个名为users的Box。然后,我们创建了一个简单的Flutter应用,允许用户输入名字和年龄,并将这些信息存储到Hive中。最后,我们读取存储的用户信息并在SnackBar中显示。

请确保你已经运行了flutter pub run build_runner build来生成user.g.dart文件,否则你的代码将无法编译。

回到顶部