forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
valuenotifier-in-flutter.dart
105 lines (94 loc) · 2.59 KB
/
valuenotifier-in-flutter.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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
class DynamicToolTipTextField extends StatelessWidget {
final TextInputType? keyboardType;
final ValueNotifier<String?> hint;
final TextEditingController controller;
const DynamicToolTipTextField({
Key? key,
required this.hint,
required this.controller,
this.keyboardType,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: hint,
builder: (context, value, child) {
return TextField(
keyboardType: keyboardType,
controller: controller,
decoration: InputDecoration(
hintText: value as String?,
),
);
},
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
@immutable
abstract class HasText {
String get text;
}
enum Hint { pleaseEnterYourEmail, youForgotToEnterYourEmail }
extension GetText on Hint {
String get text {
switch (this) {
case Hint.pleaseEnterYourEmail:
return 'Please enter your email';
case Hint.youForgotToEnterYourEmail:
return 'You forgot to enter your email';
}
}
}
class _HomePageState extends State<HomePage> {
late final ValueNotifier<String?> _hint;
late final TextEditingController _controller;
@override
void initState() {
_hint = ValueNotifier<String?>(Hint.pleaseEnterYourEmail.text);
_controller = TextEditingController();
super.initState();
}
@override
void dispose() {
_hint.dispose();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('ValueNotifier in Flutter'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
DynamicToolTipTextField(
hint: _hint,
controller: _controller,
keyboardType: TextInputType.emailAddress,
),
TextButton(
onPressed: () async {
final email = _controller.text;
if (email.trim().isEmpty) {
_hint.value = Hint.youForgotToEnterYourEmail.text;
await Future.delayed(const Duration(seconds: 2));
_hint.value = Hint.pleaseEnterYourEmail.text;
}
},
child: const Text('Log in'),
)
],
),
),
);
}
}