1、首先引入插件
event_bus: ^1.1.0
2、然后创建个event_util.dart
import 'package:event_bus/event_bus.dart';
export 'dart:async';
class EventBusUtil {
static EventBus _eventBus;
static EventBus getInstance() {
if (_eventBus == null) {
_eventBus = new EventBus();
}
return _eventBus;
}
}
class PageEvent{
String test;
PageEvent(this.test);
}
3、然后创建第一个页面event_bus_demo.dart
import 'package:demo/demo/event/event_bus_demo2.dart';
import 'package:demo/demo/event/event_util.dart';
import 'package:flutter/material.dart';
class EventBusDemo extends StatefulWidget {
@override
_EventBusDemoState createState() => _EventBusDemoState();
}
class _EventBusDemoState extends State<EventBusDemo> {
StreamSubscription<PageEvent> sss;
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
FlatButton(
onPressed: () {
sss = EventBusUtil.getInstance().on<PageEvent>().listen((data) {
print('${data.test}');
sss.cancel();
});
Navigator.push(context,
MaterialPageRoute(builder: (context) => EventBusDemo2()));
},
child: Text('点我进入下一页'),
),
],
),
);
}
}
4、接着创建第二个页面event_bus_demo2.dart
import 'package:demo/demo/event/event_util.dart';
import 'package:flutter/material.dart';
class EventBusDemo2 extends StatefulWidget {
@override
_EventBusDemo2State createState() => _EventBusDemo2State();
}
class _EventBusDemo2State extends State<EventBusDemo2> {
StreamSubscription<PageEvent> sss;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: FlatButton(
onPressed: () {
EventBusUtil.getInstance().fire(PageEvent('我是测试'));
},
child: Text('点我网上一页传值'),
),
));
}
}
此时点击按钮将会把"我是测试"这四个字传个上一个页面