forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
usestate-in-flutter-hooks.dart
93 lines (84 loc) · 2.1 KB
/
usestate-in-flutter-hooks.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
// Free Flutter Course 💙 https://linktr.ee/vandadnp
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'package:flutter_hooks/flutter_hooks.dart';
import 'dart:math' show min;
@immutable
class VirtualTab {
final Icon icon;
final String text;
const VirtualTab({
required this.icon,
required this.text,
});
}
const tabs = [
VirtualTab(
icon: Icon(Icons.picture_as_pdf),
text: 'All PDF files',
),
VirtualTab(
icon: Icon(Icons.ac_unit_outlined),
text: 'Data page',
),
VirtualTab(
icon: Icon(Icons.person),
text: 'Profile page',
),
];
class HomePage extends HookWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final tabCount = useState(1);
return DefaultTabController(
length: tabCount.value,
initialIndex: tabCount.value - 1,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: tabs
.take(tabCount.value)
.map((tab) => Tab(icon: tab.icon))
.toList(),
),
),
body: CustomTabBarView(tabCount: tabCount),
),
);
}
}
class CustomTabBarView extends StatelessWidget {
const CustomTabBarView({
Key? key,
required this.tabCount,
}) : super(key: key);
final ValueNotifier<int> tabCount;
@override
Widget build(BuildContext context) {
return TabBarView(
children: tabs
.take(tabCount.value)
.map(
(tab) => Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(tab.text),
TextButton(
onPressed: () {
final newLength = min(
tabs.length,
tabCount.value + 1,
);
tabCount.value = newLength;
},
child: const Text('Create next tab'),
)
],
),
),
)
.toList(),
);
}
}