I am new to Flutter and BloC so I wanted to create a project to improve my knowledge about them.
Down below you can see the dart files.
bnb_cubit.dart
class AppBottomNavigationBarCubit extends Cubit<AppBottomNavigationBarState> {
AppBottomNavigationBarCubit()
: super(AppBottomNavigationBarState(selectedIndex: 0));
void change(int index) =>
emit(AppBottomNavigationBarState(selectedIndex: index));
}
bnb_state.dart
class AppBottomNavigationBarState {
int selectedIndex;
AppBottomNavigationBarState({required this.selectedIndex});
}
bnb.dart
class AppBottomNavigationBar extends StatelessWidget {
AppBottomNavigationBar({super.key});
final List<Widget> screens = [HomeScreen(), SearchScreen(), LibraryScreen()];
@override
Widget build(BuildContext context) {
return BlocBuilder<AppBottomNavigationBarCubit,
AppBottomNavigationBarState>(
builder: (context, state) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home_filled),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.library_books),
label: "Home",
),
],
onTap: (value) {
context.read<AppBottomNavigationBarCubit>().change(value);
},
currentIndex:
context.read<AppBottomNavigationBarState>().selectedIndex,
),
body: screens[state.selectedIndex],
);
},
);
}
}
main.dart
Future<void> main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<AppBottomNavigationBarCubit>(
create: (context) => AppBottomNavigationBarCubit(),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AppBottomNavigationBar(),
),
);
}
}
In bnb.dart file if I use
context.read<AppBottomNavigationBarState>().selectedIndex
to change the currentIndex field of the BottomNavigationBar, application throws:
The following ProviderNotFoundException was thrown building
BlocBuilder<AppBottomNavigationBarCubit,
AppBottomNavigationBarState>
But if I change that line to
state.selectedIndex
it works fine, i wonder why is that.
My second question is that, would you use BloC for creating a BottomNavigationBar?
Thanks in advance!
CodePudding user response:
You need to read AppBottomNavigationBarCubit
to get the current state.
So it will be
currentIndex:
context.read<AppBottomNavigationBarCubit>().state.selectedIndex,
CodePudding user response:
You should access it using Cubit
context.read<AppBottomNavigationBarCubit>().state.selectedIndex
not State
context.read<AppBottomNavigationBarState>()
Since you're only providing AppBottomNavigationBarCubit
not AppBottomNavigationBarState
:
return BlocProvider<AppBottomNavigationBarCubit>()
you're getting error couldn't find correct provider