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 回复

更多关于Flutter可停止事件传播插件bus_stoppable_widget的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter插件bus_stoppable_widget来停止事件传播的代码案例。bus_stoppable_widget是一个假设的插件名称,因为Flutter生态系统中没有一个确切叫这个名字的插件,但我会基于常见的需求(如事件拦截和处理)来构建一个类似的示例。

在Flutter中,通常我们会使用GestureDetector来处理手势事件,并可以通过onPanDown, onTapDown等回调来拦截事件。如果要实现一个可以停止事件传播的自定义组件,我们可以创建一个自定义的StatefulWidget,并在其中处理手势事件。

以下是一个简单的示例,展示了如何创建一个可以停止事件传播的自定义组件:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Event Propagation Stop Example'),
        ),
        body: Center(
          child: GestureDetector(
            onTap: () {
              print('Outer GestureDetector tapped');
            },
            child: Container(
              color: Colors.lightBlue,
              width: 200,
              height: 200,
              child: BusStoppableWidget(
                onTap: (details) {
                  print('BusStoppableWidget tapped');
                  // Return true to stop propagation
                  return true;
                },
                child: Center(
                  child: Text('Tap Me'),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class BusStoppableWidget extends StatefulWidget {
  final GestureTapDownCallback? onTap;
  final Widget child;

  BusStoppableWidget({required this.onTap, required this.child});

  @override
  _BusStoppableWidgetState createState() => _BusStoppableWidgetState();
}

class _BusStoppableWidgetState extends State<BusStoppableWidget> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (details) {
        if (widget.onTap != null) {
          final stopPropagation = widget.onTap!(details);
          if (stopPropagation == true) {
            // Stop further propagation of the tap event
            return;
          }
        }
        // If not stopped, continue with default behavior (or add custom behavior here)
      },
      child: widget.child,
    );
  }
}

在这个示例中,我们创建了一个BusStoppableWidget,它接受一个GestureTapDownCallback回调(类似于onTapDown),以及一个子组件。当在BusStoppableWidget上触发onTapDown事件时,它会调用传入的回调,并根据回调的返回值决定是否停止事件的进一步传播。

  • 如果回调返回true,事件传播将被停止。
  • 如果回调返回false或没有返回值(即默认情况),事件将继续传播(在这个示例中,它将传播到外层的GestureDetector)。

这个模式可以用来创建更复杂的组件,这些组件可以根据需要在内部处理事件,并决定是否允许这些事件继续传播到父组件。虽然这个示例没有直接使用一个名为bus_stoppable_widget的插件,但它展示了如何在Flutter中实现类似的功能。

回到顶部