步骤
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().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().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);
},
),
],
),
),
);
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦