Flutter应用事件监听插件app_event的使用

Flutter应用事件监听插件app_event的使用

app_event 插件帮助你轻松管理事件,无需使用流。你可以通过将事件添加到所需的类中来管理这些事件。

sdcdc drawio

使用方法

1. 创建接收器

实现 AppEventInterface 接口以创建接收器。

class Receiver implements AppEventInterface {
  [@override](/user/override)
  onEventReceived(String eventName, value) {
    if (eventName == "testEvent") {
      // todo: 更新操作
    }
  }
}

2. 注册事件

将你的事件名称与实现 AppEventInterface 的类注册。

AppEvent.register("testEvent", Model);

3. 分发事件

在需要的时候分发事件。

AppEvent.dispatch("testEvent");

4. 接收事件

无需额外操作,所有预定义的 onEventReceived 函数会自动执行。

[@override](/user/override)
onEventReceived(String eventName, value) {
  if (eventName == "testEvent") {
      // todo: 更新操作
  }
}

5. 取消注册事件

当你不再使用该事件时,取消注册该事件。

AppEvent.unRegister("testEvent");

完整示例

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

import 'package:app_event/app_event.interface.dart';
import 'package:app_event/app_event.source.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AppEventExample',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'AppEventExample'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final test1 = TestModel1();

  [@override](/user/override)
  void initState() {
    super.initState();

    AppEvent.register("test1", test1);
  }

  void _callEvent() {
    AppEvent.dispatch("test1");
    setState(() {});
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _Button(text: test1.text),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _callEvent,
        tooltip: '更新',
        child: Container(
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(24.0)),
          child: const Text("更新"),
        ),
      ),
    );
  }
}

class _Button extends StatelessWidget {
  const _Button({
    required this.text,
  });

  final String text;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Colors.blueAccent, borderRadius: BorderRadius.circular(12.0)),
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0),
      child: Text(
        text,
        style: const TextStyle(color: Colors.white),
      ),
    );
  }
}

class TestModel1 implements AppEventInterface {
  String text = "等待";
  int number = 0;

  [@override](/user/override)
  onEventReceived(String eventName, value) {
    switch (eventName) {
      case "test1":
        break;
      default:
    }
    if (eventName == "test1") {
      number++;
      text = "接收到文本 $number";
    }
  }
}

更多关于Flutter应用事件监听插件app_event的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用事件监听插件app_event的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


app_event 是一个 Flutter 插件,用于监听应用程序生命周期事件和系统事件。它可以帮助开发者更好地管理应用程序的状态,例如当应用程序进入后台、回到前台、设备屏幕锁定等事件。

安装 app_event 插件

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

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

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

使用 app_event 插件

1. 导入 app_event 插件

import 'package:app_event/app_event.dart';

2. 初始化 AppEvent

main 函数中初始化 AppEvent

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  AppEvent.initialize();
  runApp(MyApp());
}

3. 监听应用程序事件

你可以在 initState 方法中开始监听应用程序事件,并在 dispose 方法中停止监听。

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

class _MyAppState extends State<MyApp> {
  StreamSubscription<AppLifecycleState>? _subscription;

  [@override](/user/override)
  void initState() {
    super.initState();
    _subscription = AppEvent.appLifecycleStream.listen((state) {
      print('AppLifecycleState: $state');
      // 在这里处理应用程序生命周期事件
    });
  }

  [@override](/user/override)
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AppEvent Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('AppEvent Example'),
        ),
        body: Center(
          child: Text('Check the console for lifecycle events.'),
        ),
      ),
    );
  }
}

4. 监听系统事件

app_event 还支持监听系统事件,例如屏幕锁定、解锁等。你可以通过 AppEvent.systemEventStream 来监听这些事件。

class _MyAppState extends State<MyApp> {
  StreamSubscription<SystemEvent>? _systemSubscription;

  [@override](/user/override)
  void initState() {
    super.initState();
    _systemSubscription = AppEvent.systemEventStream.listen((event) {
      print('SystemEvent: $event');
      // 在这里处理系统事件
    });
  }

  [@override](/user/override)
  void dispose() {
    _systemSubscription?.cancel();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AppEvent Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('AppEvent Example'),
        ),
        body: Center(
          child: Text('Check the console for system events.'),
        ),
      ),
    );
  }
}
回到顶部