Skip to content

Instantly share code, notes, and snippets.

@muhiro12
Created September 23, 2021 04:08
Show Gist options
  • Save muhiro12/1398458112fdc7589f5e604c91331107 to your computer and use it in GitHub Desktop.
Save muhiro12/1398458112fdc7589f5e604c91331107 to your computer and use it in GitHub Desktop.
class App extends ConsumerWidget {
const App({Key? key}) : super(key: key);
List<BottomTabItem> get _items => BottomTabItem.values;
@override
Widget build(BuildContext context, WidgetRef ref) {
final BottomTab bottomTab = ref.watch(bottomTabProvider);
final int currentIndex = _items.indexOf(bottomTab.item);
return MaterialApp(
home: Scaffold(
body: IndexedStack(
index: currentIndex,
children: _items
.map(
(BottomTabItem item) => item.page,
)
.toList(),
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) => bottomTab.select(_items[index]),
currentIndex: currentIndex,
items: _items
.map(
(BottomTabItem item) => BottomNavigationBarItem(
icon: Icon(item.icon),
label: item.label,
),
)
.toList(),
),
),
);
}
}
final ChangeNotifierProvider<BottomTab> bottomTabProvider =
ChangeNotifierProvider<BottomTab>((_) => BottomTab());
class BottomTab extends ChangeNotifier {
BottomTabItem _item = BottomTabItem.home;
BottomTabItem _oldItem = BottomTabItem.home;
BottomTabItem get item => _item;
BottomTabItem get oldItem => _oldItem;
void select(BottomTabItem newItem) {
_oldItem = _item;
_item = newItem;
notifyListeners();
}
}
enum BottomTabItem {
home,
list,
settings,
}
extension BottomTabItemExtension on BottomTabItem {
IconData get icon {
switch (this) {
case BottomTabItem.home:
return Icons.home;
case BottomTabItem.list:
return Icons.list;
case BottomTabItem.settings:
return Icons.settings;
}
}
String get label {
switch (this) {
case BottomTabItem.home:
return 'Home';
case BottomTabItem.list:
return 'List';
case BottomTabItem.settings:
return 'Settings';
}
}
Widget get page {
switch (this) {
case BottomTabItem.home:
return const HomePage();
case BottomTabItem.list:
return const LongListPage();
case BottomTabItem.settings:
return const SettingsPage();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment