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<MyHomePage> {
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: <Widget>[
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);
},
),
],
),
),
);
}
}
---
[参考](https://mp.weixin.qq.com/s?__biz=Mzg5MDAzNzkwNA==&mid=2247483795&idx=1&sn=4ea10f4d6987a592b84885a271219849&chksm=cfe3f26cf8947b7a75e567280cd86270bb7f32abdfb3c596e325459ce8599884396328efcc6e&scene=178&cur_album_id=1566028536430247937#rd)
![file](https://img.haomeiwen.com/i122666/b0036e6f67138fbe.png)
---
### Flutter 写的app, 需要源码可以私信~~
* [简繁火星字体转换](https://apps.apple.com/us/app/id1200287949)
* [哄女友神器](https://apps.apple.com/us/app/id1481044153)
* [号码测吉凶](https://apps.apple.com/us/app/id1206856799)
* [电视节目直播表](https://apps.apple.com/us/app/id1185666225)
---
### 最好的笔记软件
https://www.wolai.com/signup?invitation=6Z8Z3BP