1.添加flutter event_bus

官方链接见event_bus

pubspec.yaml添加event_bus依赖

1
  event_bus: ^2.0.0

2.示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';

class CounterEvent {
  int count;

  CounterEvent(this.count);
}

class EventBusWidget extends StatefulWidget {
  const EventBusWidget({super.key});

  @override
  EventBusWidgetState createState() => EventBusWidgetState();
}

class EventBusWidgetState extends State<EventBusWidget> {
  int _counter = 0;
  final eventBus = EventBus();

  @override
  void initState() {
    super.initState();
    eventBus.on<CounterEvent>().listen((event) {
      setState(() {
        _counter = event.count;
      });
    });
  }

  @override
  void dispose() {
    eventBus.destroy();
    super.dispose();
  }

  void _incrementCounter() {
    _counter++;
    eventBus.fire(CounterEvent(_counter));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text('the counter value is'),
        Text(
          '$_counter',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
        ElevatedButton(
            onPressed: () {
              _incrementCounter();
            },
            child: const Text('增加计数counter'))
      ],
    );
  }
}