Skip to content

Instantly share code, notes, and snippets.

@tianhaoz95
Created October 10, 2019 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tianhaoz95/cc2be8996dc1944239b5aaa1f4bc4431 to your computer and use it in GitHub Desktop.
Save tianhaoz95/cc2be8996dc1944239b5aaa1f4bc4431 to your computer and use it in GitHub Desktop.
Bottom nav bar that remembers tap state
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Rock Paper Scissors',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
/// This defines the state under the hood
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
/// If the widget needs to persist its state, we can
/// no longer use stateless widget.
class _MyHomePageState extends State<MyHomePage> {
/// We define the current focused index here
/// it keeps track of which button is currently
/// being tapped, and it should change every time
/// a new tap event happens.
int _currentIndex = 0;
final List<BottomNavigationBarItem> navItemList = [
BottomNavigationBarItem(
icon: Icon(Icons.casino),
title: Text('Rock!'),
),
BottomNavigationBarItem(
icon: Icon(Icons.casino),
title: Text('Paper!'),
),
BottomNavigationBarItem(
icon: Icon(Icons.casino),
title: Text('Scissor!'),
)
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Rock Paper Scissors')),
body: Center(child: Text('Coming soon ...')),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0,
/// Here we update the tap event handler to
/// update the state of tap, updating
/// _currentIndex with the new one that
/// is being tapped
onTap: (int index) {
setState(() {
_currentIndex = index;
});
},
items: navItemList,
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment