Error: Type argument 'RoutesBloc' doesn't conform to the bound 'BlocBase<S>' of the type variable 'B' on 'BlocBuilder' - flutter

I'm getting this error and I have no clue where it's coming from.
class Routes extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocBuilder<RoutesBloc, RoutesEvent>( // <-- It occurs here
builder: (context, state) {
return Text('...');
},
);
}
}
Full error:
lib/screens/home_screen.dart:86:12: Error: Type argument 'RoutesBloc' doesn't conform to the bound 'BlocBase' of the type variable 'B' on 'BlocBuilder'.
'RoutesBloc' is from '/blocs/routes/routes_bloc.dart' ('lib/blocs/routes/routes_bloc.dart').
'BlocBase' is from 'package:bloc/src/bloc.dart' ('../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/bloc-7.0.0/lib/src/bloc.dart').
Try changing type arguments so that they conform to the bounds.
return BlocBuilder<RoutesBloc, RoutesEvent>(
^
I use a multiplocprovider in my main.dart like this:
MultiBlocProvider(
providers: [
...,
BlocProvider<RoutesBloc>(
create: (_) => RoutesBloc(
apiRepository: ApiRepository.create(),
)..add(RoutesLoaded()),
),
],
child: AppView(),
)
routes_state.dart:
abstract class RoutesState extends Equatable {
const RoutesState();
#override
List<Object> get props => [];
}
class RoutesLoadInProgress extends RoutesState {}
class RoutesLoadSuccess extends RoutesState {
final List<BoulderingRoute> routes;
const RoutesLoadSuccess([this.routes = const []]);
#override
List<Object> get props => [routes];
}
class RoutesLoadFailure extends RoutesState {}
routes_event.dart:
abstract class RoutesEvent extends Equatable {
const RoutesEvent();
#override
List<Object> get props => [];
}
class RoutesLoaded extends RoutesEvent {}
class RouteAdded extends RoutesEvent {
final BoulderingRoute route;
const RouteAdded({this.route}) : assert(route != null);
#override
List<Object> get props => [route];
}
class RouteUpdated extends RoutesEvent {
final BoulderingRoute route;
const RouteUpdated({this.route}) : assert(route != null);
#override
List<Object> get props => [route];
}
class RouteDeleted extends RoutesEvent {
final BoulderingRoute route;
const RouteDeleted({this.route}) : assert(route != null);
#override
List<Object> get props => [route];
}
routes_bloc.dart:
class RoutesBloc extends Bloc<RoutesEvent, RoutesState> {
final ApiRepository _apiRepository;
RoutesBloc({ApiRepository apiRepository})
: assert(apiRepository != null),
this._apiRepository = apiRepository,
super(RoutesLoadInProgress());
#override
Stream<RoutesState> mapEventToState(
RoutesEvent event,
) async* {
print(event);
if (event is RoutesLoaded) {
yield* _mapRoutesLoadedToState();
}
}
Stream<RoutesState> _mapRoutesLoadedToState() async* {
try {
print('start');
final List<BoulderingRoute> routes =
await _apiRepository.fetchBoulderingRoutes();
yield RoutesLoadSuccess(routes);
} catch (_) {
yield RoutesLoadFailure();
}
}
}
I firstly thought that there must be something wrong with my RoutesBloc but changing the blocbuilder to a bloc that I'm successfully using at another place ends up with the same error.
Does someone know where this is coming from?

It should be return BlocBuilder<RoutesBloc, RoutesState>
Check this: https://pub.dev/packages/flutter_bloc#blocbuilder
BlocBuilder<BlocA, BlocAState>(
builder: (context, state) {
// return widget here based on BlocA's state
}
)

Related

State is not yielded thus unable to change icon color

I'm working on a metronome app and having problem with the bloc states. I'm toggling the metronome on and off with a FAB button and expecting the FAB icon color to change upon toggling. Could you have a look at the code and direct me towards what I am doing wrong here?
/// EVENTS
abstract class MetronomeEvent extends Equatable {
const MetronomeEvent();
#override
List<Object> get props => [];
}
class InitMetronomeEvent extends MetronomeEvent {}
class DisposeMetronomeEvent extends MetronomeEvent {}
class ToggleOnOffMetronomeEvent extends MetronomeEvent {}
class IncreaseTempoMetronomeEvent extends MetronomeEvent {}
class DecreaseTempoMetronomeEvent extends MetronomeEvent {}
class ChangeTempoMetronomeEvent extends MetronomeEvent {
final int givenTempo;
const ChangeTempoMetronomeEvent({required this.givenTempo});
#override
List<Object> get props => [givenTempo];
#override
String toString() {
return 'ChangeTempoMetronomeEvent{givenTempo: $givenTempo}';
}
}
Here is the states:
/// STATES
abstract class MetronomeState extends Equatable {
const MetronomeState();
}
class MetronomeInitial extends MetronomeState {
#override
List<Object> get props => [];
}
class ToggleOnOffMetronomeState extends MetronomeState {
final bool isMetronomeOn;
const ToggleOnOffMetronomeState({required this.isMetronomeOn});
#override
List<Object?> get props => [isMetronomeOn];
}
And my bloc:
/// BLOC
class MetronomeBloc extends Bloc<MetronomeEvent, MetronomeState> {
final _metronome = getIt<MetronomeService>();
MetronomeBloc() : super(MetronomeInitial()) {
on<InitMetronomeEvent>((event, emit) {
_metronome.init();
});
on<DisposeMetronomeEvent>((event, emit) {
_metronome.dispose();
});
on<ToggleOnOffMetronomeEvent>((event, emit) {
_metronome.toggleOnOff();
emit(ToggleOnOffMetronomeState(isMetronomeOn: _metronome.isMetronomeOn));
debugPrint("TOGGLED METRONOME ${_metronome.isMetronomeOn ? "ON" : "OFF"}");
});
on<IncreaseTempoMetronomeEvent>((event, emit) {
_metronome.increaseTempo();
});
on<DecreaseTempoMetronomeEvent>((event, emit) {
_metronome.decreaseTempo();
});
on<ChangeTempoMetronomeEvent>((event, emit) {
_metronome.changeTempo(event.givenTempo);
});
}
}
And I'm using BlocBuilder to listen and rebuild the widget below:
FloatingActionButton(
onPressed: () {
_bloc.add(ToggleOnOffMetronomeEvent());
},
child: BlocBuilder<MetronomeBloc, MetronomeState>(
builder: (context, state) {
if (state is ToggleOnOffMetronomeState) {
_isMetronomeOn = state.isMetronomeOn;
}
return Icon(
Icons.power_settings_new,
color: _isMetronomeOn
? Colors.red
: Theme
.of(context)
.floatingActionButtonTheme
.backgroundColor,
);
},
),
)

When I use Bloc pattern My infinite list doesn't scroll

I want to make infinite list with bloc pattern but My bloc builder works only 1 time.After scroll the page "yield" doesn't work so bloc builder doesn't build.The new items comes but state doesn't build.
deliveries_bloc.dart:
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_asten_app/data/orders_repository.dart';
import 'package:flutter_asten_app/models/order_list.dart';
import '../../locater.dart';
part 'deliveries_event.dart';
part 'deliveries_state.dart';
class DeliveriesBloc extends Bloc<DeliveriesEvent, DeliveriesState> {
final OrdersRepository ordersRepository = getIt<OrdersRepository>();
DeliveriesBloc() : super(DeliveriesInitial());
List<OrderList> orderss = [];
#override
Stream<DeliveriesState> mapEventToState(
DeliveriesEvent event,
) async* {
if (event is FetchDeliveriesEvent) {
yield DeliveriesLoadingState();
try {
final orders = await ordersRepository.getOrderList(event.page);
print(orders.length);
yield DeliveriesLoadedState(orders: orders);
} catch (_) {
yield DeliveriesErrorState();
}
} else if (event is FetchMoreDeliveriesEvent) {
try {
final orders = await ordersRepository.getMoreOrderList(event.page);
print(orders.length); //this is for check the orders length
yield DeliveriesLoadedState(orders: orders);
} catch (_) {
yield DeliveriesErrorState();
}
}
}
}
You can see in the above when my event is FetchMoreDeliveriesEvent my orders lengths icreases but the yield DeliveriesLoadedState(orders: orders); doesn't work
deliveries_state.dart:
part of 'deliveries_bloc.dart';
abstract class DeliveriesState extends Equatable {
const DeliveriesState();
}
class DeliveriesInitial extends DeliveriesState {
#override
List<Object> get props => [];
}
class DeliveriesLoadingState extends DeliveriesState {
#override
// TODO: implement props
List<Object> get props => throw UnimplementedError();
}
class DeliveriesLoadedState extends DeliveriesState {
final List<OrderList> orders;
DeliveriesLoadedState({#required this.orders});
#override
// TODO: implement props
List<Object> get props => [orders];
}
class DeliveriesErrorState extends DeliveriesState {
#override
// TODO: implement props
List<Object> get props => throw UnimplementedError();
}
deliveries_event.dart:
part of 'deliveries_bloc.dart';
abstract class DeliveriesEvent extends Equatable {
const DeliveriesEvent();
}
class FetchDeliveriesEvent extends DeliveriesEvent {
final int page;
FetchDeliveriesEvent({#required this.page});
#override
// TODO: implement props
List<Object> get props => [page];
}
class FetchMoreDeliveriesEvent extends DeliveriesEvent {
final int page;
FetchMoreDeliveriesEvent({#required this.page});
#override
// TODO: implement props
List<Object> get props => [page];
}
the part of Main_page
Expanded(
child: BlocBuilder<DeliveriesBloc, DeliveriesState>(
bloc: _ordersBloc,
builder: (context, DeliveriesState state) {
if (state is DeliveriesLoadingState) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is DeliveriesLoadedState) {
return ListView.builder(
controller: _scrollController,
itemCount: state.orders.length,
itemBuilder: (context, index) {
return Card(
elevation: 4,
child: ListTile(
title: Text(state.orders[index].firadi),
subtitle: Text(state.orders[index].sidttr
.toString()),
),
);
});
} else {
return null;
}
},
),
),
Bloc builder re-build the widgets only if its content changes. Make sure you are providing your change detectable variables to your equatable's props getter.
If your OrderList class is not extending from Equatable, the orders fields change won't be reflected in state.
Check if you extended your OrderList class with Equatable, if yes make sure you added its props as well.

Using a bloc with Navigator 2.0

Hi I am trying to use a bloc instead of ChangeNotifierDelegate in my RouterDelegate class. Unfortunately the bloc is not being called when a route is changed through my routebloc, not sure why. I have tried wrapping the delegate in a BlocProvider, but it made no difference (I currently have it injected above in the main file.)
runApp(MyApp());
class _MyApp AppState extends State<MyApp> {
MyAppRouterDelegate _routerDelegate = MyAppRouterDelegate();
MyAppRouteInformationParser _routeInformationParser = MyAppRouteInformationParser();
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
lazy: false,
create: (context) => getIt<AuthBloc>()//..add(AppStarted()),
),
BlocProvider(
lazy: false,
create: (context) => getIt<RouterBloc>(),
),
],
child: MaterialApp.router(
title: 'MyApp',
theme: globalAppThemeData,
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
),
);
}
}
In my RouterDelegate I have .....
lass MyAppRouterDelegate extends RouterDelegate<MyAppConfiguration>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<MyAppConfiguration> {
final GlobalKey<NavigatorState> _navigatorKey;
String currentPage = '';
String selectedItem = '';
#override
GlobalKey<NavigatorState> get navigatorKey => _navigatorKey;
MyAppRouterDelegate() : _navigatorKey = GlobalKey<NavigatorState>();
#override
MyAppConfiguration get currentConfiguration {
currentPage = currentConfiguration.screen;
selectedItem = currentConfiguration.selectedItemId;
if (currentPage == UNKNOWN) {
return MyAppConfiguration.unknown();
} else if (currentPage == SPLASH) {
return MyAppConfiguration.splash();
} else if (currentPage == LOGIN) {
return MyAppConfiguration.login();
} else {
return MyAppConfiguration.unknown();
}
}
#override
Widget build(BuildContext context) {
List<Page> pages = [SplashPage(SPLASH)];
return BlocBuilder<RouterBloc, RouterState>(
builder: (context, state) {
if (state is ChangedRoute) {
pages.clear();
pages = state.pages;
}
return Navigator(
key: navigatorKey,
pages: pages,
onPopPage: (route, result) {
if (!route.didPop(result)) return false;
context.read<AuthBloc>().add(AuthEventLoggedOut());
return true;
},
);
},
);
}
#override
Future<void> setNewRoutePath(MyAppConfiguration configuration) async {
if (configuration.unknown) {
currentPage = UNKNOWN;
selectedItem = configuration.selectedItemId;
} else if (configuration.isSplashPage) {
currentPage = SPLASH;
selectedItem = configuration.selectedItemId;
} else if (configuration.isLoginPage) {
currentPage = LOGIN;
selectedItem = configuration.selectedItemId;
} else if (configuration.isSignUpPage)
currentPage = SIGNUP;
selectedItem = configuration.selectedItemId;
} else {
print(Constants.failureCouldNotSetRoute);
}
}
_clear() {
currentPage = UNKNOWN;
selectedItem = '';
}
}
In my app configuration...
class MyAppInformationParser
extends RouteInformationParser<MyAppConfiguration> {
#override
Future<MyAppConfiguration> parseRouteInformation(RouteInformation? routeInformation) async {
final uri = Uri.parse(routeInformation!.location!);
if (uri.pathSegments.length == 0) {
return MyAppConfiguration.splash();
} else if (uri.pathSegments.length == 1) {
final first = uri.pathSegments[1].toLowerCase();
if (first == LOGIN) {
return MyAppConfiguration.login();
} else {
return MyAppConfiguration.unknown();
}
} else {
return MyAppConfiguration.unknown();
}
}
#override
RouteInformation restoreRouteInformation(MyAppConfiguration configuration) {
if (configuration.isUnknownPage) {
return RouteInformation(location: '/unknown');
} else if (configuration.isSplashPage) {
return RouteInformation(location: '/splash');
} else if (configuration.isLoginPage) {
return RouteInformation(location: '/login');
} else {
return RouteInformation(location: '/unknown');
}
}
}
My auth bloc ...
#injectable
class AuthBloc extends Bloc<AuthEvent, AuthState> {
IAuthFacade authRepo;
RouterBloc routerBloc;
AuthBloc(this.authRepo, this.routerBloc) : super(Uninitialized());
#override
Stream<AuthState> mapEventToState(
AuthEvent event,
) async* {
if (event is AppStarted) {
yield AuthenticationLoading();
Option<CurrentUser> user = await authRepo.getSignedInUser();
yield user.fold(() {
routerBloc.add(RouterEventNewPage(pages: [LoginPage(LOGIN)]));
return Unauthenticated();
}, (user) {
routerBloc.add(RouterEventNewPage(pages: [HomePage(HOME)]));
return Authenticated(user);
});
}
if (event is AuthEventLoggedOut) {
authRepo.signOut();
///TODO: clear hive here??
}
}
}
abstract class AuthEvent extends Equatable {
#override
List<Object> get props => [];
}
//
class AppStarted extends AuthEvent {}
//
class AuthEventLoggedOut extends AuthEvent {}
abstract class AuthState extends Equatable {
#override
List<Object> get props => [];
}
//
class Uninitialized extends AuthState {}
//
class Authenticated extends AuthState {
final CurrentUser user;
Authenticated(this.user);
}
//
class Unauthenticated extends AuthState {}
//
class AuthenticationLoading extends AuthState {}
My Router Bloc...
#injectable
class RouterBloc extends Bloc<RouterEvent, RouterState> {
RouterBloc() : super(RouterInitial());
#override
Stream<RouterState> mapEventToState(
RouterEvent event,
) async* {
if (event is RouterEventNewPage) {
yield ChangingRoute();
yield ChangedRoute(pages: event.pages);
}
}
}
abstract class RouterEvent extends Equatable {
const RouterEvent();
#override
List<Object> get props => [];
}
class RouterEventNewPage extends RouterEvent {
final List<Page> pages;
RouterEventNewPage({required this.pages});
#override
List<Object> get props => [pages];
}
abstract class RouterState extends Equatable {
const RouterState();
#override
List<Object> get props => [];
}
class RouterInitial extends RouterState {}
class ChangingRoute extends RouterState {}
class ChangedRoute extends RouterState {
final List<Page> pages;
ChangedRoute({required this.pages});
#override
List<Object> get props => [pages];
}
The app runs through the Navigator in the build function of the delegate first, it navigates to the splash screen perfectly, then after my animation finishes in the splash screen it calls the auth bloc to check if user is authorised, this works perfectly which then calls the routerbloc. The router bloc adds the new login screen (as the user is logged out). However, the bloc inside the build function of the MyAppRouterDelegate is not firing again.
Any help provided would be very much appreciated.
When it runs through the MyAppRouterDelegates build function the first time I do receive the error
"
════════ Exception caught by scheduler library ═════════════════════════════════
The following StackOverflowError was thrown during a scheduler callback:
Stack Overflow
When the exception was thrown, this was the stack
#0 CrokettRouterDelegate.currentConfiguration
package:crokett/routes/crokett_router_delegate.dart:20
"
But I don't receive any more information on the error.
Don't you need a notifyListeners() somewhere in your blocBuilder after you update the page stack?
I am interested to know if you got it working.

Flutter Bloc How to update Widget in BlocBuilder from the Widget itself?

How can to update a Bloc widget from the bloc Widget itself with the Slider?
The Event for the Chart Data is executed from another Widget.
When the data is fetched this Widget is opened.
When I change the Slider I want the chart to be updated withe the date but keep the other data.
Would be too much to fetch all the Data again.
How can I get access only the data changed from the same widget?
I have the following Bloc Builder Widget, bloc_event, bloc and bloc_state
The Widget:
class ChartWidget extends StatelessWidget {
ChartWidget({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
double valueSliderDate;
return BlocBuilder<ChartDataBloc, ChartDataState>(
builder: (context, state) {
if (state is ChartDataLoadInProgress) {
return LoadingIndicator();
} else if (state is ChartDataLoadSuccess) {
final chartData = state.chartData;
final maxValueAll = getMaxValueAll(chartData);
final List<double> dates = getValuesDate(chartData);
valueSliderDate = dates.first;
return Column(children: <Widget>[
Expanded(
child: MyFancyChart(chartData, valueSliderDate),
),
Slider(
min: dates.first,
max: dates.last,
divisions: dates.length,
value: valueSliderDate,
onChanged: (value) {
context.read<ChartDataBloc>().add(DateSliderSet(value));
},
),
]);
} else {
return Container();
}
},
);
}
This is the bloc_event with two events:
abstract class ChartDataEvent {
const ChartDataEvent();
#override
List<Object> get props => []; }
class SpecificIndicatorIdSet extends ChartDataEvent {
const SpecificIndicatorIdSet(this.indicator);
final Indicator indicator;
#override
List<Object> get props => [indicator]; }
class DateSliderSet extends ChartDataEvent {
const DateSliderSet(this.dateSlider);
final double dateSlider;
#override
List<Object> get props => [dateSlider]; }
This is the bloc itself:
class ChartDataBloc extends Bloc<ChartDataEvent, ChartDataState> {
final ChartDataRepository chartDataRepository;
ChartDataBloc({#required this.chartDataRepository}) : super(ChartDataLoadInProgress());
#override
Stream<ChartDataState> mapEventToState(ChartDataEvent event) async* {
if (event is SpecificIndicatorIdSet) {
yield* _mapIndicatorsLoadedToState(event);
} else if (event is DateSliderSet) {
yield* _mapDateSliderToState(event); } }
Stream<ChartDataState> _mapDateSliderToState(
DateSliderSet event
) async* {
try {
final dateSlider = event.dateSlider;
yield DateSliderLoadSuccess(
dateSlider,
);
} catch (_) {
yield DateSliderLoadFailure(); } }
Stream<ChartDataState> _mapIndicatorsLoadedToState(
SpecificIndicatorIdSet event
) async* {
try {
final chartData = await this.chartDataRepository.loadChartData(event.indicator.id);
yield ChartDataLoadSuccess(
sortToListOfLists(chartData),
event.indicator.name
);
} catch (_) {
yield ChartDataLoadFailure(); } } }
This is the bloc_state:
abstract class ChartDataState {
const ChartDataState();
#override
List<Object> get props => []; }
class ChartDataLoadInProgress extends ChartDataState {}
class ChartDataLoadSuccess extends ChartDataState {
final List<List<ChartData>> chartData;
final String titleIndicator;
const ChartDataLoadSuccess(this.chartData,this.titleIndicator);
#override
List<Object> get props => [chartData, titleIndicator];
#override
String toString() => 'ChartDataLoadSuccess { topics: ' + chartData + ' }'; }
class ChartDataLoadFailure extends ChartDataState {}
class DateSliderLoadSuccess extends ChartDataState {
final double dateSlider;
const DateSliderLoadSuccess(this.dateSlider);
#override
List<Object> get props => [dateSlider];
#override
String toString() => 'DateSliderLoadSuccess { dateSlider: ' + dateSlider.toString() + ' }';
}
class DateSliderLoadFailure extends ChartDataState {}
Thanks in advance
Have you tried creating a variable inside your bloc to store the original data?
You would be able to store the data and be able to continue using your bloc and updating your widget.

How to change state of individual list items using bloc flutter?

How to change the widgets in a list item in flutter using bloc pacakage.
Should i use BlockBuilder or listener on the whole ListView.builder or only the individual items.
It would be nice if u share an example or tutorial.
eg If i have a checkbox i need to change its state on clicking it.
These are my Bloc classes
Bloc
const String SERVER_FAILURE_MESSAGE = 'Server Failure';
const String CACHE_FAILURE_MESSAGE = 'Cache Failure';
class MarkAttendanceBloc extends Bloc<MarkAttendanceEvent, MarkAttendanceState> {
final MarkStudentPresent markStudentPresent;
final MarkStudentAbsent markStudentAbsent;
MarkAttendanceBloc({#required this.markStudentPresent,#required this.markStudentAbsent});
#override
MarkAttendanceState get initialState => MarkedInitial();
#override
Stream<MarkAttendanceState> mapEventToState(MarkAttendanceEvent event) async* {
yield MarkedLoading();
if(event is MarkAbsentEvent){
final remotelyReceived = await markStudentAbsent(MarkStudentParams(classId: event.classId, courseId: event.courseId,studentId: event.studentId));
yield* _eitherLoadedOrErrorState(remotelyReceived);
}
else if(event is MarkPresentEvent){
final remotelyReceived = await markStudentPresent(MarkStudentParams(classId: event.classId, courseId: event.courseId,studentId: event.studentId));
yield* _eitherLoadedOrErrorState(remotelyReceived);
}
}
Stream<MarkAttendanceState> _eitherLoadedOrErrorState(
Either<StudentDetailsFacultyFailure,int> failureOrClasses,
) async* {
yield failureOrClasses.fold(
(failure) => MarkedError(_mapFailureToMessage(failure)),
(studentId) => Marked(studentId),
);
}
String _mapFailureToMessage(StudentDetailsFacultyFailure failure) {
switch (failure.runtimeType) {
case ServerError:
return SERVER_FAILURE_MESSAGE;
default:
return 'No internet';
}
}
}
State
abstract class MarkAttendanceState extends Equatable{
const MarkAttendanceState();
}
class MarkedInitial extends MarkAttendanceState{
const MarkedInitial();
#override
List<Object> get props => [];
}
class MarkedLoading extends MarkAttendanceState{
const MarkedLoading();
#override
List<Object> get props => [];
}
class Marked extends MarkAttendanceState{
final int studentId;
Marked(this.studentId);
#override
List<Object> get props => [studentId];
}
class MarkedError extends MarkAttendanceState{
final String errorMessage;
MarkedError(this.errorMessage);
#override
List<Object> get props => [errorMessage];
}
Event
import 'package:equatable/equatable.dart';
abstract class MarkAttendanceEvent extends Equatable {
const MarkAttendanceEvent();
}
class MarkPresentEvent extends MarkAttendanceEvent {
final int studentId;
final int courseId;
final int classId;
MarkPresentEvent(this.studentId, this.courseId, this.classId);
#override
List<Object> get props =>[studentId,courseId,classId];
}
class MarkAbsentEvent extends MarkAttendanceEvent {
final int studentId;
final int courseId;
final int classId;
MarkAbsentEvent(this.studentId, this.courseId, this.classId);
#override
List<Object> get props =>[studentId,courseId,classId];
}
Maybe by now you have found a solution but this is how i managed to achieve the same functionality using flutter cubits.
This code is hand written and not tested but it should guide you to achieve your goal
1 Declare the class objects
class ClassItem{
int? price;
bool isChecked;
ClassItem({
this.price,
this.isChecked=false,
});
}
class ClassOverall{
List<ClassItem> items;
double? total;
ClassOverall(this.items,this.total);
}
Declare the cubit class
class OverallCubit extends Cubit<ClassOverall> {
OverallCubit(ClassOverallinitialState) : super(initialState);
void checkUncheckCart(int index) {
if (!state.items
.elementAt(index).isChecked) {
state.items
.elementAt(index).isChecked =
!state.items
.elementAt(index).isChecked;
var t_total = double.tryParse(state.items
.elementAt(index).price!)! * 1;
emit(OverallCubit (state.items,state.total));
} else {
state.items.elementAt(index).isChecked =
!state.items
.elementAt(index).isChecked;
emit(OverallCubit (state.items,state.total));
}
calculateTotal();
}
void calculateTotal() {
var tot = 0.0;
for (var tick in state.items) {
if (tick.isChecked) {
tot = (tick.t_total! + tot);
}
}
emit(OverallCubit (state.items,tot));
}
}
Declare the top class widget to hold the state
class TopState extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => OverallCubit(ClassOverall(items,0)),//fetch items from your source
child: Home(),
);
}
}
Declare the stateful widget and add a bloc builder
class Home extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<Home> {
#override
Widget build(BuildContext context) {
return BlocBuilder<OverallCubit, ClassOverall>(
builder: (ctx, state) {
return Column(children:[
ListView.builder(
padding: EdgeInsets.all(0.0),
shrinkWrap: true,
itemCount: state.items.length,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
ctx
.read<OverallCubit>()
.checkUncheckCart(index);
},
tileColor: state.elementAt(index).isChecked ? Colors.red : Colors.white
title: Text(state.items.elementAt(index).price!),
);
}),
Text(state.total.toString),
]);
});
}
}