Flutter核心数据存储插件micro_core_store的使用

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

Flutter核心数据存储插件micro_core_store的使用

许可证

许可证 包版本 包积分 覆盖率

平台支持

Android iOS MacOS Web Linux Windows

特性

  • 基于状态模式
  • 封装一个流来管理屏幕的状态
  • 监听流事件以在特定状态发生时采取行动
  • 根据存储的状态构建小部件

使用

创建状态

sealed class ListNamesStates {}

final class InitialListNamesState extends ListNamesStates {}

final class LoadingListNamesState extends ListNamesStates {}

final class ErrorListNamesState extends ListNamesStates {
  final Exception exception;

  ErrorListNamesState(this.exception);
}

final class SuccessListNamesState extends ListNamesStates {
  final List<String> names;

  SuccessListNamesState(this.names);
}

创建存储

final class ListNamesStore extends Store<ListNamesStates> {
  ListNamesStore(this._listNames) : super(InitialListNamesState());

  final Future<List<String>> Function() _listNames;

  [@override](/user/override)
  void onInit() {
    super.onInit();
    listNames();
  }

  void listNames() async {
    emit(LoadingListNamesState());

    try {
      final names = await _listNames();
      emit(SuccessListNamesState(names));
    } on Exception catch (exception) {
      emit(ErrorListNamesState(exception));
    }
  }
}

创建使用存储构建器的页面

class ListNamesSuccessBody extends StatelessWidget {
  const ListNamesSuccessBody({super.key, required this.namesList});

  final List<String> namesList;

  [@override](/user/override)
  Widget build(BuildContext context) {
    if (namesList.isEmpty) {
      return const Center(
        child: Text('No name was found!'),
      );
    }

    return ListView.separated(
      itemBuilder: (context, index) => ListTile(title: Text(namesList[index])),
      separatorBuilder: (context, index) => const Divider(),
      itemCount: namesList.length,
    );
  }
}

class ListNamesPage extends StatefulWidget {
  const ListNamesPage({super.key, required this.listNamesStore});

  final ListNamesStore listNamesStore;

  [@override](/user/override)
  State<ListNamesPage> createState() => _ListNamesPageState();
}

class _ListNamesPageState extends State<ListNamesPage> {
  [@override](/user/override)
  void initState() {
    super.initState();

    // 创建监听器以监听状态的变化。
    //
    // 在这里你可以定义一些规则,以便在出现特定状态时显示对话框、Snackbar或导航到另一个屏幕。
    widget.listNamesStore.addListener(
      (state) => switch (state) {
        InitialListNamesState() => onInitialState(),
        LoadingListNamesState() => onLoadingState(),
        ErrorListNamesState() => onErrorState(state.exception),
        SuccessListNamesState() => onSuccessState(state.names),
      },
    );
  }

  [@override](/user/override)
  void dispose() {
    widget.listNamesStore.dispose();
    super.dispose();
  }

  void onInitialState() {
    log('onInitialState');
  }

  void onLoadingState() {
    log('onLoadingState');
  }

  void onErrorState(Exception exception) {
    log('onErrorState - ${exception.toString()}');
  }

  void onSuccessState(List<String> names) {
    log('onSuccessState - $names');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Names List'),
        centerTitle: true,
      ),
      body: StoreBuilder<ListNamesStore, ListNamesStates>(
        store: widget.listNamesStore,
        builder: (context, state) => switch (state) {
          InitialListNamesState() || LoadingListNamesState() => const Center(child: CircularProgressIndicator()),
          ErrorListNamesState() => Center(child: Text('Exception - ${state.exception.toString()}')),
          SuccessListNamesState() => ListNamesSuccessBody(namesList: state.names),
        },
      ),
    );
  }
}

完整示例

import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:micro_core_store/micro_core_store.dart';

sealed class ListNamesStates {}

final class InitialListNamesState extends ListNamesStates {}

final class LoadingListNamesState extends ListNamesStates {}

final class ErrorListNamesState extends ListNamesStates {
  final Exception exception;

  ErrorListNamesState(this.exception);
}

final class SuccessListNamesState extends ListNamesStates {
  final List<String> names;

  SuccessListNamesState(this.names);
}

final class ListNamesStore extends Store<ListNamesStates> {
  ListNamesStore(this._listNames) : super(InitialListNamesState());

  final Future<List<String>> Function() _listNames;

  [@override](/user/override)
  void onInit() {
    super.onInit();
    listNames();
  }

  void listNames() async {
    emit(LoadingListNamesState());

    try {
      final names = await _listNames();
      emit(SuccessListNamesState(names));
    } on Exception catch (exception) {
      emit(ErrorListNamesState(exception));
    }
  }
}

class ListNamesSuccessBody extends StatelessWidget {
  const ListNamesSuccessBody({super.key, required this.namesList});

  final List<String> namesList;

  [@override](/user/override)
  Widget build(BuildContext context) {
    if (namesList.isEmpty) {
      return const Center(
        child: Text('No name was found!'),
      );
    }

    return ListView.separated(
      itemBuilder: (context, index) => ListTile(title: Text(namesList[index])),
      separatorBuilder: (context, index) => const Divider(),
      itemCount: namesList.length,
    );
  }
}

class ListNamesPage extends StatefulWidget {
  const ListNamesPage({super.key, required this.listNamesStore});

  final ListNamesStore listNamesStore;

  [@override](/user/override)
  State<ListNamesPage> createState() => _ListNamesPageState();
}

class _ListNamesPageState extends State<ListNamesPage> {
  [@override](/user/override)
  void initState() {
    super.initState();

    // 创建监听器以监听状态的变化。
    widget.listNamesStore.addListener(
      (state) => switch (state) {
        InitialListNamesState() => onInitialState(),
        LoadingListNamesState() => onLoadingState(),
        ErrorListNamesState() => onErrorState(state.exception),
        SuccessListNamesState() => onSuccessState(state.names),
      },
    );
  }

  [@override](/user/override)
  void dispose() {
    widget.listNamesStore.dispose();
    super.dispose();
  }

  void onInitialState() {
    log('onInitialState');
  }

  void onLoadingState() {
    log('onLoadingState');
  }

  void onErrorState(Exception exception) {
    log('onErrorState - ${exception.toString()}');
  }

  void onSuccessState(List<String> names) {
    log('onSuccessState - $names');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Names List'),
        centerTitle: true,
      ),
      body: StoreBuilder<ListNamesStore, ListNamesStates>(
        store: widget.listNamesStore,
        builder: (context, state) => switch (state) {
          InitialListNamesState() || LoadingListNamesState() => const Center(child: CircularProgressIndicator()),
          ErrorListNamesState() => Center(child: Text('Exception - ${state.exception.toString()}')),
          SuccessListNamesState() => ListNamesSuccessBody(namesList: state.names),
        },
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何使用Flutter中的micro_core_store插件进行数据存储的示例代码。micro_core_store是一个轻量级的状态管理库,非常适合在Flutter应用中进行核心数据的存储和管理。不过需要注意的是,micro_core_store可能并不是一个广泛知名的库,以下示例基于假设其功能类似于其他常见的Flutter状态管理库。

首先,确保你已经在pubspec.yaml文件中添加了micro_core_store的依赖(如果真实存在的话,否则请替换为类似的库,如providerriverpod等):

dependencies:
  flutter:
    sdk: flutter
  micro_core_store: ^x.y.z  # 替换为实际的版本号

然后,运行flutter pub get来获取依赖。

接下来,我们创建一个简单的Flutter应用,展示如何使用micro_core_store(或类似库)进行数据存储和管理。以下是一个基本的示例:

import 'package:flutter/material.dart';
import 'package:micro_core_store/micro_core_store.dart'; // 假设包名正确

// 定义一个简单的状态模型
class CounterState {
  int count;

  CounterState({required this.count});

  CounterState copyWith({int? count}) {
    return CounterState(count: count ?? this.count);
  }
}

// 定义一个Store来管理状态
class CounterStore extends Store<CounterState> {
  CounterStore() : super(CounterState(count: 0));

  void increment() {
    setState(state.copyWith(count: state.count + 1));
  }
}

void main() {
  // 创建Store的实例
  final counterStore = CounterStore();

  runApp(
    StoreProvider<CounterState>(
      store: counterStore,
      child: MyApp(),
    ),
  );
}

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 使用StoreConnector来连接Store和UI
    return StoreConnector<CounterState>(
      converter: (store) => store.state,
      builder: (context, counterState) {
        final counterStore = StoreProvider.of<CounterState>(context).store;

        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter Demo Home Page'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '${counterState.count}',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              counterStore.increment();
            },
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      },
    );
  }
}

注意:上面的代码示例中,micro_core_storeStoreProvider等组件是假设存在的。实际上,如果你发现micro_core_store不是一个真实存在的库,你可以考虑使用providerriverpod等流行的状态管理库,它们的用法非常相似。

例如,使用provider库的话,你可以这样修改:

dependencies:
  flutter:
    sdk: flutter
  provider: ^x.y.z  # 替换为实际的版本号

然后,在代码中相应地替换为provider的组件和方法。希望这个示例能帮助你理解如何在Flutter中进行核心数据的存储和管理。如果有更多具体需求或问题,欢迎继续提问!

回到顶部