In Android native, there are broadcasts for transferring data across pages. Flutter allows you to customize an event bus to transfer data across pages. steps

  • Define a singleton class
  • Add a Map

    variable that holds the name of the listening event and the corresponding CallBack method.
    ,callback>
  • Add the ON method to add events to the map.
  • Add the off method to remove event listeners from the map.
  • Defines emit methods for event sources to emit events.

Event bus:

// The subscriber callback signature typedef void EventCallback(arg); Class EventBus {// Private constructor eventbus._internal (); Static EventBus _singleton = new eventbus._internal (); // Factory constructor factory EventBus()=> _singleton; Var _emap = new Map<String, EventCallback>(); / / add the subscriber void on (eventName, EventCallback f) {if (eventName = = null | | f = = null) return; _emap[eventName]=f; } void off(eventName) {_emap[eventName] = null; Void emit(eventName, [arg]) {var f = _emap[eventName]; f(arg); }}Copy the code

Test page:

class EventBusTest extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'RaisedButton', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'RaisedButton'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> {var bus = new EventBus(); int index = 1; String text = ''; @override void initState() { super.initState(); Bus. on("key0", (parmas){text= parmas.tostring (); }); bus.on("key1", (parmas){text=parmas.toString(); }); bus.on("key2", (parmas){text=parmas.toString(); }); } @override void dispose() { super.dispose(); // Remove listener bus.off("key0") when widget is closed; bus.off("key1"); bus.off("key2"); } @override Widget build(BuildContext context) {return Scaffold(appBar: appBar (// nav title: [// Navigation bar right menu IconButton(icon: icon (icon.share), onPressed: () {}),],), body: <Widget> Center(Child: Text(Text),), floatingActionButton: floatingActionButton (// Hover button Child: Text("emit"), onPressed: _onAdd,// click call method),); } void _onAdd() { index++; SetState (() {// emit bus.emit(getNameByIndex(index), index); }); } String getNameByIndex(index){ if(index%3==0){ return 'key0'; } if(index%3==1){ return 'key1'; } if(index%3==2){ return 'key2'; }}}Copy the code