-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
115 lines (99 loc) · 2.84 KB
/
main.dart
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import 'package:flutter/widgets.dart';
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
final media = MediaQueryData.fromView(View.of(context));
return MediaQuery(
data: media,
child: Directionality(
textDirection: TextDirection.ltr,
child: MessageHandler(
message: 'message',
child: Builder(builder: (context) {
final message = MessageHandler.of(context);
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 50),
child: Text(message),
),
GestureDetector(
onTap: () {
MessageHandler.update(context, (message) => '$message.');
},
child: const Text('Click me to append a dot'),
),
],
),
);
}),
),
),
);
}
}
class MessageHandler extends StatefulWidget {
const MessageHandler({
super.key,
required this.message,
required this.child,
});
final String message;
final Widget child;
static String? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<_InheritedMessage>()?.message;
static String of(BuildContext context) {
final message = maybeOf(context);
assert(message != null, 'cannot find $MessageHandler in context');
return message!;
}
static void update(
BuildContext context,
String Function(String raw) updater,
) {
final handler =
context.dependOnInheritedWidgetOfExactType<_InheritedMessage>();
if (handler != null) handler.update(updater(handler.message));
}
@override
State<MessageHandler> createState() => _MessageHandlerState();
}
class _MessageHandlerState extends State<MessageHandler> {
late String _message = widget.message;
void update(String message) {
if (_message != message) {
setState(() {
_message = message;
});
}
}
@override
void didUpdateWidget(covariant MessageHandler oldWidget) {
super.didUpdateWidget(oldWidget);
update(widget.message);
}
@override
Widget build(BuildContext context) => _InheritedMessage(
message: _message,
update: update,
child: widget.child,
);
}
class _InheritedMessage extends InheritedWidget {
const _InheritedMessage({
required this.message,
required this.update,
required super.child,
});
final String message;
final void Function(String message) update;
@override
bool updateShouldNotify(covariant _InheritedMessage oldWidget) =>
message != oldWidget.message;
}