we have a BottomNavigationBarItem and one icon has Notification counter,
we want to update that counter (notificationCounter) from any page Like from Business(), School(),
how we achieve this?
Please ignore this repeated text i had to do it because stack overflow telling me i have a lot of code and not enough of text they are not allowing me to put my question( this bug need to be reported to stack overflow) because im not having a lot of code its normal in flutter and my question is short
thanks
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
int notificationCounter = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Home(),
Business(),
School(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Badge(
showBadge: true,
badgeContent: Text(notificationCounter.toString(), style: const TextStyle(fontSize: 10.0, color: Colors.white)),
animationType: BadgeAnimationType.scale,
shape: BadgeShape.circle,
child: const Icon(Icons.notifications),
),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
CodePudding user response:
I would suggest looking at using the Providers package for ChangeNotifierProvider. Once you wrap your main build with a changenotifier, let the changenotifier file handle values like counters, then it will update the relevant widgets automatically (as the providers are wrapped around / accessed by all your widgets).
https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html https://pub.dev/packages/provider
CodePudding user response:
This should solve it for you,
Declare int _currentIndex = 0;
in the state of your class
bottomNavigationBar: BottomNavigationBar(
backgroundColor: kMainBgColor,
onTap: (int index) {
setState(() {
_currentIndex = index;
});
},
selectedItemColor: Colors.white,
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
backgroundColor: kCardBgColor,
activeIcon: Image.asset('assets/images/home.png',width: 24,height: 24,color: kNavVioletColor,),
icon: Image.asset('assets/images/home.png',width: 24,height: 24,),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.update),
label: "New"
),
BottomNavigationBarItem(
icon: Icon(Icons.done),
label: "New"
)
],
),