flutter eventbus往上一个页面传值

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 {
  StreamSubscription sss;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          FlatButton(
            onPressed: () {
              sss = EventBusUtil.getInstance().on().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 {
  StreamSubscription sss;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      child: FlatButton(
        onPressed: () {
          EventBusUtil.getInstance().fire(PageEvent('我是测试'));
        },
        child: Text('点我网上一页传值'),
      ),
    ));
  }
}

此时点击按钮将会把"我是测试"这四个字传个上一个页面

你可能感兴趣的:(Flutter)