Flutter中央管理插件centralstation的功能使用

Flutter中央管理插件centralstation的功能使用

Central Station 是一个用于 Flutter 的简单命令/事件处理引擎。

引言

什么是命令?

  • 命令是一些程序步骤的序列,用于执行状态变更。
  • 我们希望命令被执行。
  • 执行命令可能会产生结果。
  • 例如:“获取股票代码X的报价”。

什么是事件?

  • 事件表示某些事情已经发生。
  • 事件是状态变更的证据。
  • 例如:“已获得股票代码X的报价,价格为Y。”

特性

  • 命令通常需要更多时间来执行。
  • 命令可能会引发一些事件,这些事件需要通知其他组件以进行展示或跟踪。
  • 命令在执行过程中可能会失败。
  • 单个命令将由单个处理器处理该命令。
  • 单个事件可以被多个组件监听。

开始使用

假设我们有一个获取股票报价的命令和相应的事件:

class GetStockQuoteCommand {
  final String code;
  GetStockQuoteCommand(this.code);
}

class StockQuoteObtainedEvent {
  final String code;
  final num price;
  StockQuoteObtainedEvent(this.code, this.price);
}

/// 实现
Stream getStockQuote(dynamic command) async* {
  var cmd = command as GetStockQuoteCommand;
  num price = await ... // 进行网络操作;

  dispatchEvent(StockQuoteObtainedEvent(cmd.code, price)); // 通知其他组件

  yield price; // 命令结果
}

要使用 Central Station,首先初始化运行时环境:

final CentralStationRuntime runtime = CentralStationRuntime(
  commandHandlers: {
    GetStockQuoteCommand: getStockQuote,
  },
  eventHandlers: [],  // 如果有事件处理器,请设置此选项
);

在小部件构建期间初始化 CentralStation:

Widget build(BuildContext context) {
  return MaterialApp(
    home: CentralStation(
      runtime: runtime,
      child: ... // 像平常一样构建您的小部件
    ),
  );
}

在某个时刻执行命令,如下所示:

RaisedButton(
  key: btnKey,
  child: Text("获取报价!"),
  onPressed: () async {
    var stockPrice = await CentralStation.sendCommand(context, GetStockQuoteCommand(this.code)).first;
    setState(() {
      // 更新UI
      this.price = stockPrice;
    });
  },
),

还有其他一些有趣的特性,如命令链、显示等待文本等。

在实际项目中,我使用了 Central Station 与 BLOC 模式结合(使用事件处理器将事件桥接到 BLOC 的 dispatch 方法),这使得项目易于管理。

欢迎探索其他可能性,并期待您的反馈。

进一步阅读

示例代码

以下是一个完整的示例代码,展示了如何使用 centralstation 插件。

import 'package:flutter/material.dart';

import "package:centralstation/centralstation.dart";
import 'command.dart';
import 'event.dart';

void main() {
  CentralStationRuntime runtime = CentralStationRuntime(
    commandHandlers: {
      GetStockQuoteCommand: getStockQuote,
    },
    eventHandlers: [],
  );

  runApp(MaterialApp(
    home: CentralStation(
      runtime: runtime,
      child: MyHomePage(),
    ),
  ));
}

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

class _MyHomePageState extends State<MyHomePage> {
  String _price = "";

  void _getStockQuote() async {
    var stockPrice = await CentralStation.sendCommand(context, GetStockQuoteCommand("X")).first;
    setState(() {
      _price = stockPrice.toString();
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Central Station 示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '股票价格:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              _price,
              style: TextStyle(fontSize: 20),
            ),
            RaisedButton(
              onPressed: _getStockQuote,
              child: Text('获取报价'),
            )
          ],
        ),
      ),
    );
  }
}

更多关于Flutter中央管理插件centralstation的功能使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter中央管理插件centralstation的功能使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


CentralStation 是一个用于 Flutter 应用的状态管理插件,它提供了一种简单而高效的方式来管理应用程序的状态。虽然 CentralStation 并不是 Flutter 官方推荐的插件,但它的设计理念类似于其他状态管理工具,如 ProviderRiverpod,旨在简化状态管理的过程。

以下是 CentralStation 的基本功能和使用方法:

1. 安装 CentralStation

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

dependencies:
  flutter:
    sdk: flutter
  centralstation: ^1.0.0  # 请根据实际版本号进行替换

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

2. 创建状态管理类

CentralStation 允许你创建一个状态管理类来管理应用的状态。你可以通过继承 CentralStation 类来实现这一点。

import 'package:centralstation/centralstation.dart';

class CounterState extends CentralStation {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners(); // 通知监听器状态已更新
  }
}

在这个例子中,CounterState 类管理着一个简单的计数器状态,并提供了一个 increment 方法来增加计数器的值。

3. 在应用中提供状态

为了在整个应用中访问 CounterState,你需要在应用的顶层使用 CentralStationProvider 来提供这个状态。

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

void main() {
  runApp(
    CentralStationProvider(
      create: (_) => CounterState(),
      child: MyApp(),
    ),
  );
}

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

4. 在 UI 中使用状态

你可以使用 CentralStation.of<T>() 方法来获取状态,并在 UI 中使用它。

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

class CounterScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counterState = CentralStation.of<CounterState>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('CentralStation Demo'),
      ),
      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: () => counterState.increment(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

在这个例子中,CounterScreen 通过 CentralStation.of<CounterState>(context) 获取 CounterState 实例,并在 UI 中显示计数器的值。当用户点击浮动操作按钮时,计数器的值会增加,并且 UI 会自动更新。

5. 监听状态变化

CentralStation 自动处理状态变化的通知。当你调用 notifyListeners() 时,所有依赖该状态的 UI 组件都会自动重建。

6. 多个状态管理

你可以创建多个状态管理类,并在应用的不同部分使用它们。只需在 CentralStationProvider 中提供这些状态即可。

CentralStationProvider(
  create: (_) => CounterState(),
  child: CentralStationProvider(
    create: (_) => AnotherState(),
    child: MyApp(),
  ),
)
回到顶部