步骤
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);
},
),
],
),
),
);
}
}