I’m trying to implement a bottom navigation bar with bloc. I defined a function, which will control the navigation. The function is inside a BLoC. My problem is, that I cannot access this function. I tried to define it outside an -function, but it still doesn’t work. What did I do wrong here?
landingpage.dart relevant part
import 'package:flutter/material.dart';
import 'package:flutter_application_1/prensentation/LandingPage/bloc/landing_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
.
.
bottomNavigationBar: BlocBuilder<LandingBloc, NavigationState>(
builder: (context, state) {
return BottomNavigationBar(
currentIndex: state.index,
showSelectedLabels: false,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "home"),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: "settings"),
BottomNavigationBarItem(
icon: Icon(Icons.account_box), label: "account")
],
onTap: (index) {
//this doesn't work
if (index == 0) {
BlocProvider.of<LandingBloc>(context).
.getNavBarItem(NavbarItem.settings)
} else if (index == 1) {
BlocProvider.of<LandingBloc>(context);
.getNavBarItem(NavbarItem.settings);
} else if (index == 2) {
BlocProvider.of<LandingBloc>(context);
.getNavBarItem(NavbarItem.profile);
}
},
);
landing_bloc, landing_event, landing_state
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_application_1/prensentation/LandingPage/nav_bar_items.dart';
import 'package:meta/meta.dart';
part 'landing_event.dart';
part 'landing_state.dart';
//BLoC
class LandingBloc extends Bloc<LandingEvent, NavigationState> {
LandingBloc() : super(NavigationState(NavBarItem.home, 0)) {
on<LandingInitial>((event, emit) {
// TODO: implement event handler
void getNavBarItem(NavBarItem navbarItem) {
switch (navbarItem) {
case NavBarItem.home:
emit(NavigationState(NavBarItem.home, 0));
break;
case NavBarItem.setting:
emit(NavigationState(NavBarItem.setting, 1));
break;
case NavBarItem.profile:
emit(NavigationState(NavBarItem.profile, 2));
break;
}
}
});
}
}
//Events
part of 'landing_bloc.dart';
@immutable
abstract class LandingEvent {}
class LandingInitial extends LandingEvent {}
//States
part of 'landing_bloc.dart';
class NavigationState extends Equatable {
final NavBarItem navbarItem;
final int index;
NavigationState(this.navbarItem, this.index);
@override
List<Object> get props => [this.navbarItem, this.index];
}
2
Answers
In Bloc we add a event from UI part and Bloc do certain operation and emit a state. And here you have made a function inside and event code which is wrong you should add a event where you are trying to call the bloc function.
And i don’t see you have use-case for Bloc you should be using the Cubit either, it have the similar functionality you are trying to do, calling a cubit function and do operation and emit state simple.
Check out this article for Cubit
You need to add
BlocProvider
in your page to create bloc.