I'm creating a Flutter application. I'm added a BloC to my project for management state. I created a list with data. And I want to add item to ListView manually with button 'Add'.
I'm wrote a code:
My Item Cubit
class ItemCubit extends Cubit<List<Item>> {
ItemCubit() : super([]);
void addItem(item){
state.add(item);
emit(state);
}
}
Page of Items with Provider:
class SearchPage extends StatelessWidget {
const SearchPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (_) => ItemCubit(),
child: Search(),
),
);
}
}
And I call the BlocBuilder in Stateless Widget like this:
body: BlocBuilder<MarketCubit, List<Market>>(
builder: (context, items) => TabBarView(...))
So when I call my function from state:
Item item = Item(1, 'Item 1');
ElevatedButton(onPressed:(){
context.read<ItemCubit>().addItem(item);
}, child: Text('Add Item')),
The ListView doesn't updating. What's problem? Thanks a lot!
create new variable, add them to the new variable list, update your new variable list item to it, emit the data with the new variable. this is how i got it working.
late List<ServicesExpensesList> newList = <ServicesExpensesList>[];
state.utilityDataList.forEach((element) {
newList.add(element);
});
newList.insert(0, utilityData);
newList.sort((a, b) => b.createdAt.compareTo(a.createdAt));
emit(state.copyWith(
utilityDataList: newList,
status: state.status == BlocStateStatus.success
? BlocStateStatus.updated
: BlocStateStatus.success,
))