'Change DateField value using Provider
I want to change date field value while clicking on a Radio Button named "Yes". One can input date by changing date from datepicker. Another one is is user clicked on "Yes" button the datefield value will be changed. I'm trying it using Provider. But the updated value isn't displaying into datefield instantly.
Code snippet:
DateTimeFormField(
dateFormat: DateFormat('yyyy-MM-dd'),
mode: DateTimeFieldPickerMode.date,
initialValue: DateTime.parse(list[index].endDate!),
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
hintStyle: TextStyle(color: Colors.black45),
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.event_note),
),
onDateSelected: (DateTime value) {
list[index].endDate = value.toString();
},
)
##
class ManipulateDate extends ChangeNotifier {
String date = '';
void setDateToDTNow(String newDate) {
date = newDate;
notifyListeners();
}
}
Inside Button's onPressed function
Provider.of<ManipulateDate>(context, listen: false).setDateToDTNow(DateTime.now().toString());
How could I set the changed value Provider.of<ManipulateDate>(context).date into list[index].endDate and the value will display instantly while clicking on Button.
Solution 1:[1]
I guess I got the issue you have set listen: false -
Provider.of<ManipulateDate>(context, listen: false).setDateToDTNow(DateTime.now().toString());
So when you do notifylisteners() the above won't be triggered or updated so try changing that to true -
Provider.of<ManipulateDate>(context, listen: true).setDateToDTNow(DateTime.now().toString());
Or alternatively you can use a consumer widget around the part which you want to update in the UI. Hope these helps now....
Solution 2:[2]
Most likely this is because you're not listening to the provider changes in your build method, so the widget doesn't get "refreshed" when the provider is updated. Check ChangeNotifierProvider for some examples.
BTW, I highly recommend using Riverpod over Provider, as it offers a cleaner widget tree, and more flexibility in state management.
For example, you could do this:
// Outside of your class...
// Yes, as a global, but don't worry. That's actually the correct way to do it.
final selectedDateProvider = StateProvider((ref) => DateTime.now());
@override
Widget build(BuildContext context, WidgetRef ref) {
final DateTime selectedDate = ref.watch(selectedDateProvider).state;
return DateTimeFormField(
initialValue: selectedDate,
...
onDateSelected: (DateTime value) {
ref.read(selectedDateProvider).state = value;
},
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | triple7 |
