Reputation: 183
In app i am using Cubit. ItemData fetch from firestore. Everything works, but after added item in list and update value(name) in firestore, in list still old value. How to solve it?
class TestPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
BlocBuilder<ItemCubit, ItemState>(
cubit: ItemCubit(DataBase())..getItemData(item),
builder: (context, state) {
if (state is ItemData) {
return Column(
children: [
Text(state.item.name),
RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TestPage1(
item: state.item,
)));
},
child: Text('showPage'),
),
RaisedButton(
onPressed: () {
context.bloc<TestCubit>().add(item);
},
)
],
);
}
return Container(
child: Text('error'),
);
},
)
],
),
);
}
}
for add item in list i am uisng another cubit code:
class AddCubit extends Cubit<AddState> {
AddCubit() : super(AddInitial());
List<Item> items = List<Item>();
void addItem(Item item) {
items.add(item);
emit(LoadList(items));
}
}
This is bloc for retrieve list of items in TestPage1:
BlocBuilder<AddCubit, AddState>(builder: (context, state) {
if (state is LoadList) {
return Column(
children: state.items.toSet().map((item) {
return Card(
child: Text(item.name),
);
}).toList(),
);
}
})
state code:
class LoadList extends AddState {
final List<Item> items;
LoadList(this.items);
}
Upvotes: 3
Views: 7378
Reputation: 1
just FYI. The above answer will not work 100% if you are trying to update your widget because List.add will update the state immediately (but won't call Bloc or Cubit due to how Equatable is comparing values).
So if you want to use List.add or List.remove, You simply need to execute setState somewhere.
Upvotes: 0
Reputation: 183
In flutter when you compare two objects of the same class, you will have always equality even if the values of them are different. Unless you will use equality method in your class.
Class code with equality method
import 'package:equatable/equatable.dart';
class LoadList extends AddState {
final List<Item> items;
LoadList(this.items);
@override
List<Object> get props => [items];
}
Second thing is the fact that u should use copy with and don't create new state for new value. It will come handy later and reduce the number of possible errors later on.
Whole code for state class
import 'package:equatable/equatable.dart';
class LoadList extends AddState {
final List<Item> items;
LoadList(this.items);
LoadList copyWith({
List<Item> items,
}) {
return LoadList(
items: items?? this.items,
);
}
@override
List<Object> get props => [items];
}
And then for your void function you should use:
void addItem(Item item) {
items.add(item);
emit(state.copyWith(items: items);
}
Upvotes: 7