I am new to Flutter and the BloC pattern. I am trying to create a simple counter application that has a Tab layout, in which pressing increment
and decrement
buttons will update the counter accordingly which will be displayed on tab 2.
I currently have the following:
Main.dart:
import 'package:budgetapplication/global_observer.dart';
import 'package:budgetapplication/sumpage.dart';
import 'package:flutter/material.dart';
import 'package:budgetapplication/homepage.dart';
import 'package:bloc/bloc.dart';
void main() {
Bloc.observer = const GlobalApplicationObserver();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const appTitle = 'Tab Controller Demo with BloC pattern';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.dark_mode_rounded)),
Tab(
icon: Icon(Icons.access_alarm),
)
],
)),
body: const TabBarView(children: [
HomepageTab(),
Sumpage(),
]),
),
);
}
}
Sumpage.dart:
import 'package:budgetapplication/counter_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class Sumpage extends StatelessWidget {
const Sumpage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocBuilder<CounterCubit, int>(
builder: (context, state) {
return Text('$state');
},
),
),
);
}
}
GlobalObserver.dart:
class GlobalApplicationObserver extends BlocObserver {
/// {@macro counter_observer}
const GlobalApplicationObserver();
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
print('THIS IS COMING FROM THE GlobalApplicationObserver!');
print('${bloc.runtimeType} $change');
}
}
CounterCubit.dart
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
/// Add 1 to the current state.
void increment() => emit(state + 1);
/// Subtract 1 from the current state.
void decrement() => emit(state - 1);
}
I am getting the following exception when attempting to run the application:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ProviderNotFoundException was thrown building KeyedSubtree-[GlobalKey#7958a]:
Error: Could not find the correct Provider<StateStreamable<Object?>> above this
BlocBuilder<StateStreamable<Object?>, Object?> Widget
I have tried to use the suggestion listed in the exception but for some reason i can’t compile when i use builder: (context, child) {...}
in my Homepage widget. It does the error is stemming from my Homepage widget when trying to build the child.
I am using
flutter_bloc: ^8.1.6
bloc: ^8.1.4
Any help?