Flutter可停止事件传播插件bus_stoppable_widget的使用
Flutter可停止事件传播插件bus_stoppable_widget
的使用
特征
- 内置小型事件总线
- 按需订阅事件
- 按需取消订阅事件
安装
只需要一个简单的命令即可完成安装:
flutter pub add bus_stoppable_widget
创建
将StatefulWidget
替换为BusStoppableWidget
,并将State
替换为BusStoppableState
。
使用
在需要订阅事件时,使用subscribe(String, Function(dynamic))
方法。在需要取消订阅事件时,使用unsubscribe(String)
方法。
基本情况下,当该小部件被销毁时,所有注册的事件会自动取消。在大多数情况下,你只需在需要时订阅事件。
// EVENT : 字符串
// CALLBACK : 函数(动态)
subscribe(event, callback);
// EVENT : 字符串
unsubscribe(event);
示例代码
以下是一个完整的示例代码,展示了如何使用bus_stoppable_widget
插件来管理事件的订阅与取消订阅。
import 'package:flutter/material.dart';
import 'package:bus_stoppable_widget/bus_stoppable_widget.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const ExampleApp());
}
class EventList {
static const String exampleSwitch = 'example-switch';
}
class ExampleApp extends BusStoppableWidget {
const ExampleApp({super.key});
[@override](/user/override)
BusStoppableState<ExampleApp> createState() => _ExampleAppState();
}
class _ExampleAppState extends BusStoppableState<ExampleApp> {
final Color backgroundColorOn = Colors.green;
final Color backgroundColorOff = Colors.red;
final Color textColor = Colors.white;
bool status = false;
[@override](/user/override)
void initState() {
super.initState();
// 当你需要时订阅事件
subscribe(EventList.exampleSwitch, exampleSwitchCallback);
// 当你需要时取消订阅事件
// unsubscribe(EventList.exampleSwitch);
}
[@override](/user/override)
Widget build(BuildContext context) {
Color backgroundColor = status ? backgroundColorOn : backgroundColorOff;
String text = status ? 'ON' : 'OFF';
return MaterialApp(
home: Scaffold(
body: GestureDetector(
// 当你需要时发布事件
onTap: () => publish(EventList.exampleSwitch),
child: Container(
width: double.maxFinite,
height: double.maxFinite,
color: backgroundColor,
child: Center(
child: Text(
text,
style: TextStyle(
color: textColor,
),
),
),
),
),
),
);
}
void exampleSwitchCallback(_) {
setState(() {
status = !status;
});
}
}
更多关于Flutter可停止事件传播插件bus_stoppable_widget的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复