VxState

VxState 是一个为 Flutter 应用构建的状态管理库,专注于简洁性。它受到 StoreKeeper 和 Redux、Vuex 等库的启发,并具有流的强大功能。以下是它的工作原理的基本概念

  • 单一存储(单一事实来源)以保存应用的数据
  • 使用 Mutations 对存储进行结构化修改
  • Widgets 监听 Mutations 以进行重建
  • 通过 Interceptors 和 Effects 增强此过程

VxState 的核心基于 Flutter 的 InheritedModel widget。

入门

添加到你的 pubspec

dependencies:
  ...
  vxstate: any

创建一个存储

import 'package:vxstate/vxstate.dart';

class MyStore extends VxStore {
  int count = 0;
}

定义 Mutations

class Increment extends VxMutation<MyStore> {
  perform() => store.count++;
}

监听 Mutations

@override
Widget build(BuildContext context) {
  // Define when this widget should re render
  VxState.listen(context, to: [Increment]);

  // Get access to the store
  MyStore store = VxState.store;

  return Text("${store.count}");
}

完整的示例

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

// Build store and make it part of app
void main() {
  runApp(VxState(
    store: MyStore(),
    child: MyApp(),
  ));
}

// Store definition
class MyStore extends VxStore {
  int count = 0;
}

// Mutations
class Increment extends VxMutation<MyStore> {
  perform() => store.count++;
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Define when this widget should re render
    VxState.listen(context, to: [Increment]);

    // Get access to the store
    MyStore store = VxState.store;

    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Text("Count: ${store.count}"),
            RaisedButton(
              child: Text("Increment"),
              onPressed: () {
                // Invoke mutation
                Increment();
              },
            ),
          ],
        ),
      ),
    );
  }
}

文档

  • VxStore - 应用的数据存储位置
  • VxMutation - 修改存储的逻辑
  • VxBuilder、VxNotifier、VxConsumer - 适用于特殊情况的实用 Widgets
  • VxEffect - 链式 Mutations
  • VxInterceptors - 拦截 Mutations 的执行

GitHub

https://github.com/iampawan/VxState