I have below CategoryState in my project:
part of 'categories_cubit.dart';
abstract class CategoriesState {}
class CategoriesInitial extends CategoriesState {}
class CategoriesLoaded extends CategoriesState {
final List<Category> categories;
final List<Category>? filteredData;
final int? sortIndex;
final bool sortAscending;
CategoriesLoaded({
required this.categories,
this.filteredData,
this.sortIndex,
required this.sortAscending,
});
}
//Add
class AddingCategory extends CategoriesState {}
class CategoryAdded extends CategoriesState {}
//delete
class DeletingCategory extends CategoriesState {}
class CategoryDeleted extends CategoriesState {}
//update
class UpdatingCategory extends CategoriesState {}
class CategoryUpdated extends CategoriesState {}
//error
class CategoryStateError extends CategoriesState {
String? errorMessage = "Error encoutered";
CategoryStateError({this.errorMessage});
}
Then I have this Category Page with DataTable loaded by the categories
from if state is CategoriesLoaded
.
class _CategoryPageState extends State<CategoryPage> {
final searchController = TextEditingController();
@override
Widget build(BuildContext context) {
return SizedBox(
width: 1500,
height: 1000,
child: BlocBuilder<CategoriesCubit, CategoriesState>(
builder: (context, state) {
if (state is! CategoriesLoaded) {
if (state is CategoriesInitial) {
BlocProvider.of<CategoriesCubit>(context).fetchCategories();
}
return const Center(child: CircularProgressIndicator());
}
return Container(....)
.
.
.
}
From the Category Page, I can open an Add Item Dialog. If adding category is successful, Cubit will emit CategoryAdded
state and close the dialog. Otherwise, cubit will emit CategoryStateError
state.
My problem is that once CategoryStateError
state is emit, the main Category Page beneath the dialog box becomes empty since its display data depends on CategoryLoaded
state. Is there anyway where I can retain the data in Category Page even if the state is changed in the Dialog Box operation? Or is there any better alternative for error handling using Bloc Cubit
CodePudding user response:
Try this :
class _CategoryPageState extends State<CategoryPage> {
final searchController = TextEditingController();
@override
Widget build(BuildContext context) {
return SizedBox(
width: 1500,
height: 1000,
child: BlocBuilder<CategoriesCubit, CategoriesState>(
listener: (context, state) {
if (state is! CategoriesLoaded) {
if (state is CategoriesInitial) {
BlocProvider.of<CategoriesCubit>(context).fetchCategories();
}
}
},
builder: (context, state) {
return (state is! CategoriesLoaded && state is! CategoriesInitial)?const Center(child: CircularProgressIndicator()):Container(....)
.
.
.
}
CodePudding user response:
I managed to solve my issue. Instead of creating CategoryStateError to handle the Exception, I created a new Controller and Stream where I add the error message. I do not emit a new state when there is an exception. I monitor the stream and add display the error message.