forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random-iterable-value-in-dart.dart
64 lines (56 loc) · 1.55 KB
/
random-iterable-value-in-dart.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
// Free Flutter Course 💙 https://linktr.ee/vandadnp
import 'dart:math' as math show Random;
extension RandomElement<T> on Iterable<T> {
T getRandomElement() => elementAt(
math.Random().nextInt(length),
);
}
final colors = [Colors.blue, Colors.red, Colors.brown];
class HomePage extends StatelessWidget {
final color = ValueNotifier<MaterialColor>(
colors.getRandomElement(),
);
HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('List.Random in Flutter'),
),
body: ColorPickerButton(color: color),
);
}
}
class ColorPickerButton extends StatelessWidget {
final ValueNotifier<MaterialColor> color;
const ColorPickerButton({
Key? key,
required this.color,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<Color>(
valueListenable: color,
builder: (context, value, child) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: CenteredTight(
child: TextButton(
style: TextButton.styleFrom(backgroundColor: value),
onPressed: () {
color.value = colors.getRandomElement();
},
child: const Text(
'Change color',
style: TextStyle(
fontSize: 30,
color: Colors.white,
),
),
),
),
);
},
);
}
}