I have a Bottom Navigation Bar using FlutterIcons and I would like to use either onTap() or onPressed() on them to switch between screens in the app. How can I achieve this?
Here's my code snippet:
bottomNavigationBar: CurvedNavigationBar(
backgroundColor: Constants.scaffoldBackgroundColor,
buttonBackgroundColor: Constants.primaryColor,
items: [
Icon(
FlutterIcons.ios_home_ion,
size: 20.0,
color: activeIndex == 0 ? Colors.white : Color(0xFF000B70),
),
Icon(
FlutterIcons.file_pdf_box_mco,
size: 20.0,
color: activeIndex == 1 ? Colors.white : Color(0xFF000B70),
),
Icon(
FlutterIcons.qrcode_scan_mco,
size: 20.0,
color: activeIndex == 2 ? Colors.white : Color(0xFF000B70),
),
Icon(
FlutterIcons.notifications_active_mdi,
size: 20.0,
color: activeIndex == 3 ? Colors.white : Color(0xFF000B70),
),
Icon(
FlutterIcons.setting_ant,
size: 20.0,
color: activeIndex == 4 ? Colors.white : Color(0xFF000B70),
),
],
onTap: (index) {
setState(() {
activeIndex = index;
});
},
),
CodePudding user response:
CurvedNavigationBar
doesn't provide onPressed
, use onTap
as you've define.
bottomNavigationBar: CurvedNavigationBar(
items: [
],
onTap: (index) {
setState(() {
activeIndex = index;
});
},
body:yourWidgetList[activeIndex]
),
More about curved_navigation_bar
Demo widget
class AGG extends StatefulWidget {
const AGG({Key? key}) : super(key: key);
@override
State<AGG> createState() => _AGGState();
}
class _AGGState extends State<AGG> {
List<Widget> pages = [
Text("Page 1"),
Text("Page 2"),
Text("Page 3"),
];
int activeIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: CurvedNavigationBar(
backgroundColor: Colors.blueAccent,
items: <Widget>[
Icon(Icons.add, size: 30),
Icon(Icons.list, size: 30),
Icon(Icons.compare_arrows, size: 30),
],
onTap: (index) {
setState(() {
activeIndex = index;
});
},
),
body: pages.elementAt(activeIndex),
);
}
}
You can explore more about BottomNavigationBar
CodePudding user response:
The difference between onTap() and onPressed is the moment of execution. As you can imagine onPressed() fires as soon as user touches the item without necessarily removing the finger from tap area.
onTap() fires only after full tap has been detected meaning- item has been touched and touch was quickly removed. Quickly meaning faster than gets detected by onLongPress().
To use different touch types you can wrap every navigation item individually in GestureDetector or Inkwell or wrap the whole bar in one of those and pass a parameter to detect which item has been pressed.
Think of it as difference between tapping your arm and pressing on your arm.
Use whichever makes more sense in your scenario (I'd suggest onTap()). Hope that helps.