In one of my classes i have a simple button which i update state, but in this class after changing state i can't watch to this changes
class BreadItem extends ConsumerWidget {
//...
const BreadItem({
Key? key,
//...
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Stack(
children: [
//...
Container(
height: 50.0,
/...
GestureDetector(
onTap: () {
//...
ref.read(orderStructureProvider.notifier).increment(breadId: id);
},
child: Container(
width: 40.0,
//...
),
),
Text(ref.watch(orderStructureProvider.notifier).getBreadCount(breadId: id).toString()),
],
).pSymmetric(h: 16.0),
),
],
);
}
}
as you can see i have a ref.read(orderStructureProvider.notifier).increment(breadId: id); which i incrementing bread and with ref.watch(orderStructureProvider.notifier).getBreadCount(breadId: id).toString() i want to get latest changes but it doesn't work
incrementing breads work fine and i can see changes with debugPrint
my orderStructureProvider:
final orderStructureProvider = StateNotifierProvider<OrderNotifier, OrderStructure>((ref) => OrderNotifier());
class OrderNotifier extends StateNotifier<OrderStructure> {
OrderNotifier() : super(_initial);
static const OrderStructure _initial = OrderStructure(
breads: [],
baker: [],
paymentType: 1,
);
void increment({required int breadId}) {
final int index = state.breads.indexWhere((bread) => bread.id == breadId);
final bread = state.breads[index];
final updatedBread = bread.copyWith(count: bread.count + 1);
state = state.copyWith(
breads: List.from(state.breads)..[index] = updatedBread,
);
debugPrint(state.toString());
}
int getBreadCount({required int breadId}) {
final int count= state.breads.isNotEmpty ? state.breads[state.breads.indexWhere((bread) => bread.id == breadId)].count:0;
debugPrint('$count');
return count;
}
}
@freezed
abstract class OrderStructure with _$OrderStructure {
const factory OrderStructure({
required List<BreadStructure> breads,
required List<Map<String, dynamic>> baker,
required int paymentType,
}) = _OrderStructure;
factory OrderStructure.fromJson(Map<String, dynamic> json) => _$OrderStructureFromJson(json);
}
@freezed
abstract class BreadStructure with _$BreadStructure {
const factory BreadStructure({
required int id,
required String name,
required int count,
}) = _BreadStructure;
factory BreadStructure.fromJson(Map<String, dynamic> json) => _$BreadStructureFromJson(json);
}