event_bus应用场景
本人初步接触event_bus 目前的理解是flutter 兄弟组件之间的参数传递,下面是效果图:
以下为代码实现部分:
1.先去pubspec.yaml添加插件:
event_bus: ^1.1.0
2.主页面:
import 'package:flutter/material.dart';
import 'second_page.dart';
import 'first_page.dart';
class Main_Page extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Event_Bus_Demo'),
),
body:Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//两个页面为兄弟组件
First_Page(),
Second_Page(),
],
),
),
)
);
}
}
3.Dart任何class都可以作为一个event,建立event_bus.dart
import 'package:event_bus/event_bus.dart';
//Bus初始化
EventBus eventBus = EventBus();
class UserLoggedInEvent {
String text;
UserLoggedInEvent(String text){
this.text = text;
}
}
4.first_page代码:
import 'package:flutter/material.dart';
//引入Bus
import './event_bus.dart';
class First_Page extends StatelessWidget {
String text = '我是触发事件,通过Bus传递';
@override
Widget build(BuildContext context) {
return Container(
child: InkWell(
onTap: (){
//Bus触发事件
eventBus.fire(new UserLoggedInEvent(text));
},
child: RaisedButton(
child: Text('点击我触发'),
),
),
);
}
}
5.second_page代码:
import 'package:flutter/material.dart';
//引入Bus
import './event_bus.dart';
class Second_Page extends StatefulWidget {
@override
_Second_PageState createState() => _Second_PageState();
}
class _Second_PageState extends State<Second_Page> {
var result;
//监听Bus events
void _listen(){
eventBus.on<UserLoggedInEvent>().listen((event){
setState(() {
result = event.text;
});
});
}
@override
Widget build(BuildContext context) {
_listen();
return Container(
child: Text('${result}'),
);
}
}