|
| 1 | +import 'dart:async'; |
| 2 | + |
1 | 3 | import 'package:flutter/material.dart'; |
| 4 | +import 'package:reflex/reflex.dart'; |
2 | 5 |
|
3 | 6 | void main() { |
4 | 7 | runApp(const MyApp()); |
5 | 8 | } |
6 | 9 |
|
7 | 10 | class MyApp extends StatefulWidget { |
8 | | - const MyApp({Key? key}) : super(key: key); |
| 11 | + const MyApp({ |
| 12 | + Key? key, |
| 13 | + }) : super(key: key); |
9 | 14 |
|
10 | 15 | @override |
11 | 16 | State<MyApp> createState() => _MyAppState(); |
12 | 17 | } |
13 | 18 |
|
14 | 19 | class _MyAppState extends State<MyApp> { |
| 20 | + Reflex? _reflex; |
| 21 | + StreamSubscription<NotificationEvent>? _subscription; |
| 22 | + final List<NotificationEvent> _log = []; |
| 23 | + bool started = false; |
| 24 | + |
15 | 25 | @override |
16 | 26 | void initState() { |
17 | 27 | super.initState(); |
| 28 | + initPlatformState(); |
| 29 | + } |
| 30 | + |
| 31 | + // Platform messages are asynchronous, so we initialize in an async method. |
| 32 | + Future<void> initPlatformState() async { |
| 33 | + startListening(); |
| 34 | + } |
| 35 | + |
| 36 | + void onData(NotificationEvent event) { |
| 37 | + setState(() { |
| 38 | + _log.add(event); |
| 39 | + }); |
| 40 | + debugPrint(event.toString()); |
| 41 | + } |
| 42 | + |
| 43 | + void startListening() { |
| 44 | + _reflex = Reflex(); |
| 45 | + try { |
| 46 | + _subscription = _reflex!.notificationStream!.listen(onData); |
| 47 | + setState(() { |
| 48 | + started = true; |
| 49 | + }); |
| 50 | + } on ReflexException catch (exception) { |
| 51 | + debugPrint(exception.toString()); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + void stopListening() { |
| 56 | + _subscription?.cancel(); |
| 57 | + setState(() => started = false); |
18 | 58 | } |
19 | 59 |
|
20 | 60 | @override |
21 | 61 | Widget build(BuildContext context) { |
22 | 62 | return MaterialApp( |
23 | 63 | home: Scaffold( |
24 | 64 | appBar: AppBar( |
25 | | - title: const Text('Plugin example app'), |
| 65 | + title: const Text('Reflex Example app'), |
| 66 | + ), |
| 67 | + body: Center( |
| 68 | + child: ListView.builder( |
| 69 | + itemCount: _log.length, |
| 70 | + itemBuilder: (BuildContext context, int idx) { |
| 71 | + final entry = _log[idx]; |
| 72 | + return ListTile( |
| 73 | + title: Text(entry.title ?? ""), |
| 74 | + subtitle: Text(entry.message ?? ""), |
| 75 | + trailing: Text(entry.packageName.toString().split('.').last), |
| 76 | + ); |
| 77 | + }, |
| 78 | + ), |
26 | 79 | ), |
27 | | - body: const Center( |
28 | | - child: Text('App Running!!\n'), |
| 80 | + floatingActionButton: FloatingActionButton( |
| 81 | + onPressed: started ? stopListening : startListening, |
| 82 | + tooltip: 'Start/Stop listening', |
| 83 | + child: |
| 84 | + started ? const Icon(Icons.stop) : const Icon(Icons.play_arrow), |
29 | 85 | ), |
30 | 86 | ), |
31 | 87 | ); |
|
0 commit comments