Flutter状态流管理插件streamable_state的使用

Flutter状态流管理插件streamable_state的使用

Streamable 是一个基于 StreamBuilder 的简单状态管理解决方案。要理解如何使用此插件,请参考示例应用程序。

示例代码

文件:example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:streamable_state/streamable.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> {
  /// 存储数据的类。可以存储在任何地方。
  final controller = CountController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                    onPressed: controller.add,
                    style: ButtonStyle(
                      padding: MaterialStateProperty.resolveWith(
                        (states) => const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                      ),
                    ),
                    child: const Text("增加"),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),

                    /// 处理状态更新的小部件
                    child: Streamed(
                      streamable: controller.count,
                      builder: (value) {
                        return Text(value.toString());
                      },
                    ),
                  ),
                  TextButton(
                    onPressed: controller.subtract,
                    style: ButtonStyle(
                      padding: MaterialStateProperty.resolveWith(
                        (states) => const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                      ),
                    ),
                    child: const Text("减少"),
                  ),
                ],
              ),
              Visibility(
                visible: false,
                child: Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TextButton(
                        onPressed: controller.loop,
                        style: ButtonStyle(
                          padding: MaterialStateProperty.resolveWith(
                            (states) => const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                          ),
                        ),
                        child: const Text("循环"),
                      ),
                      TextButton(
                        onPressed: controller.stop,
                        style: ButtonStyle(
                          padding: MaterialStateProperty.resolveWith(
                            (states) => const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                          ),
                        ),
                        child: const Text("停止"),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CountController {
  /// 需要观察的值,也可以是任何类型
  final count = Streamable(0);
  late Timer? timer;

  void add([int? i]) {
    final newVal = i ?? 1;
    count.value += newVal;
    count.send();
  }

  void subtract([int? i]) {
    final newVal = i ?? 1;
    count.value -= newVal;
    count.send();
  }

  void loop() {
    timer ??= Timer.periodic(Duration(milliseconds: 10), (timer) {
      add(1);
    });
  }

  void stop() {
    timer?.cancel();
    timer = null;
  }
}

更多关于Flutter状态流管理插件streamable_state的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter状态流管理插件streamable_state的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


streamable_state 是一个用于 Flutter 的状态管理插件,它基于 StreamStreamController 来实现状态管理。这个插件适合那些已经熟悉 Stream 的开发者,并且它可以帮助你在应用中轻松地管理状态。

安装

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

dependencies:
  flutter:
    sdk: flutter
  streamable_state: ^0.1.0 # 请使用最新版本

然后运行 flutter pub get 来安装插件。

基本用法

streamable_state 的核心是通过 StreamController 来管理状态,并且通过 StreamBuilder 来监听状态的变化。

1. 创建一个状态管理类

首先,你可以创建一个状态管理类,这个类将负责管理和分发状态。

import 'package:streamable_state/streamable_state.dart';

class CounterState {
  final StreamController<int> _controller = StreamController<int>.broadcast();
  int _count = 0;

  Stream<int> get stream => _controller.stream;

  void increment() {
    _count++;
    _controller.add(_count);
  }

  void dispose() {
    _controller.close();
  }
}

在这个例子中,我们创建了一个 CounterState 类,它包含一个 _controller 用于管理状态流。increment 方法用于增加计数,并将新的计数通过 _controller 发送出去。

2. 在 UI 中监听状态变化

接下来,你可以在 UI 中使用 StreamBuilder 来监听状态的变化,并更新 UI。

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

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

class MyApp extends StatelessWidget {
  final CounterState counterState = CounterState();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Streamable State Example')),
        body: Center(
          child: StreamBuilder<int>(
            stream: counterState.stream,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text('Count: ${snapshot.data}');
              } else {
                return Text('Count: 0');
              }
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => counterState.increment(),
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

在这个例子中,我们使用了 StreamBuilder 来监听 CounterState 中的 stream,并将当前的计数显示在 UI 中。当用户点击 FloatingActionButton 时,increment 方法会被调用,计数增加,UI 也会随之更新。

3. 释放资源

当不再需要 CounterState 时,记得调用 dispose 方法来释放资源,避免内存泄漏。

[@override](/user/override)
void dispose() {
  counterState.dispose();
  super.dispose();
}
回到顶部