I am having a very stupid problem.
So basically I have a custom bottom navigation bar. It was taking too much lines and indents in my home.dart
file. So I decided to extract and place it in another dart file i.e. my bottomnavbar.dart
file.
And use it in my home page like this:
child: BottomNavBar(),
but I am having trouble in changing between screens in the home page. I am having this in my home.dart
file:
int selectedIndex = 0;
final screen = [
PageOne(),
PageTwo(),
PageThree(),
PageFour(),
PageFive(),
];
Use:
///inside a stack
screen[selectedIndex],
and in my bottomnavbar.dart
file I have extracted a widget for my bottom navigation bar items
:
Widget bnbItems(
String image,
int index,
double height,
) {
return InkWell(
splashColor: Colors.pink,
onTap: () => setState(() {
selectedIndex = index;
_controller.animateTo(index / 4);
}),
child: Container(
alignment: Alignment.center,
width: 50,
height: 50,
child: Padding(
padding: const EdgeInsets.only(top: 5.0),
child: Image.asset(
image,
height: height,
),
),
),
);
}
Use:
Row(
children: [
bnbItems('assets/icons/icn1.png', 0, size.height / 25),
bnbItems('assets/icons/icn2.png', 1, size.height / 21),
bnbItems('assets/icons/icn3.png', 2, size.height / 19),
bnbItems('assets/icons/icn4.png', 3, size.height / 34),
bnbItems('assets/icons/icn5.png', 4, size.height / 21),
],
),
With this setup the screens
are not changing. It happened since I moved the BottomNavBar
to differnt file.
Any solution? Maybe by using GetX?
CodePudding user response:
When you call setState
inside your bottomnavbar.dart
you are only updating the StatefulWidget that is inside of that file, which is probably just the bottom navigation bar.
This is where you need shared state between two files, hence state management.
You could use ChangeNotifier
, but for now start simple and use ValueNotifier
create a ValueNotifier for current screen in your home page
...
final ValueNotifier<int> currentScreen;
@override
Widget build(...
pass it to your bottom navigation widget
child: BottomNavBar(currentScreen),
add the ValueNotifier as a required field in your widget
class BottomNavBar extends StatelessWidget {
const BottomNavBar({super.key, required this.currentScreen});
final ValueNotifier<int> currentScreen;
@override
Widget build(BuildContext context) {
...
now you dont need setState
in your bottom navigation bar, just edit the currentScreen.value
in your onTap
onTap: () {
currentScreen.value = index;
_controller.animateTo(index / 4);
},
Adjust the code per your project, these are just here as an example