Flutter跨组件传递事件


步骤

1. 引入第三方库

pubspec.yaml 引入 event_bus: ^1.1.1

2. 定义在组件之间传递的对象

class UserInfo {
  String nickname;
  int level;

  UserInfo(this.nickname, this.level);
}

3. 创建全局的EventBus对象

final eventBus = EventBus();

4. 在某个widget发出事件

FlatButton(
              child: Text("Testbutton", style: TextStyle(color: Colors.white)),
              color: Colors.orange, // 按钮的颜色

              onPressed: () {
                final info = UserInfo("why", 18);
                eventBus.fire(info);
              },
            ),

5. 在另一个widget监听事件

  @override
  void initState() {
    super.initState();

    eventBus.on<UserInfo>().listen((data) {
      setState(() {
        message = "${data.nickname}-${data.level}";
      });
    });
  }
    ```


---

## 完整代码

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

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

class UserInfo { String nickname; int level;

UserInfo(this.nickname, this.level); }

class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } }

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

final String title;

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

class _MyHomePageState extends State { final eventBus = EventBus();

String message = "Hello Coderwhy";

@override void initState() { super.initState();

eventBus.on<UserInfo>().listen((data) {
  setState(() {
    message = "${data.nickname}-${data.level}";
  });
});

}

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( message, style: Theme.of(context).textTheme.headline4, ), FlatButton( child: Text("Testbutton", style: TextStyle(color: Colors.white)), color: Colors.orange, // 按钮的颜色

          onPressed: () {
            final info = UserInfo("why", 18);
            eventBus.fire(info);
          },
        ),
      ],
    ),
  ),
);

} }

```


参考

Flutter跨组件传递事件

Flutter 写的app, 需要源码可以私信~~


最好的笔记软件

https://www.wolai.com/signup?invitation=6Z8Z3BP

上一篇:EventBus的简单介绍


下一篇:Guava的event bus