Closed DiegoVega19 closed 10 months ago
When developing a Flutter application using the BLoC pattern, it's crucial to manage the scope of your BLoCs/Cubits effectively. Each BLoC/Cubit should be available in the context where it's needed. Declaring all BLoCs/Cubits in your main method (root of the widget tree) can work, but it's not always the most efficient approach, especially for larger applications with multiple features or screens.
A more scalable and modular approach is to provide each BLoC/Cubit closer to where it's used. This strategy not only helps in organizing the code better but also ensures that the BLoCs/Cubits are disposed of properly when they are no longer needed, avoiding potential memory leaks and performance issues.
Here's an example of how you can wrap each page or feature in its own BlocProvider:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'my_bloc.dart'; // Import your specific BLoC
/// Wrapper widget that provides the BLoC to MyPageView.
class MyPage extends StatelessWidget {
const MyPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => MyBloc(), // Replace with your specific BLoC
child: const MyPageView(),
);
}
}
/// The page that uses the BLoC.
class MyPageView extends StatelessWidget {
const MyPageView({super.key});
@override
Widget build(BuildContext context) {
// Example usage of BlocBuilder
return BlocBuilder<MyBloc, MyState>(
builder: (context, state) {
// Build your UI based on the BLoC state
return Scaffold(
appBar: AppBar(title: Text('My Page')),
body: Center(
child: Text('State: $state'),
),
);
},
);
}
}
@DiegoVega19 u need to move ur BlocProvider "up" one level in the widget tree, because floatingActionIcon and ur BlocProvider at same level, resulting the bloc not available to Builder's context on the floatingActionIcon.
thank you guys, I managed to solve for yours advice
You can close the issue if its fixed.😀
Description I am creating a SPA application with flutter_bloc which on a single screen, I use alerts to edit, add and perform certain actions, and if I open any of the alert dialog I receive the following error "The following ProviderNotFoundException was thrown building AlertContentWidget: Error: Could not find the correct Provider above this BlocBuilder<AlertsBloc,
AlertsState> Widget",
Steps To Reproduce From here I attach a minimal reproducible example,
Expected Behavior The alert dialog should show the corresponding data
Additional Context
The error is solved putting all the blocs in the main.dart, but I don't want to do that because there are many Screens and blocs and I want to create each bloc from each screen that uses it.
I hope you can help me, I have been trying to find a solution for days but nothing has worked for me, thank you very much in advance