I want to insert a value from method showTimePicker
to list in model class that extends ChangeNotifier.
void timePicker(){
showTimePicker(context: context, initialTime: TimeOfDay.now()).then((value) {
_timeOfDay = value!;
Provider.of<GridWidgetModel(context,listen:true).addTimeList(value.format(context).toString());
});
}
class GridWidgetModel extends ChangeNotifier {
final List<String> _timeList = ["11:25", "22:15"];
UnmodifiableListView<String> get timeList => UnmodifiableListView(_timeList);
get displayList => _timeList;
void addTimeList(pickerValue){
_timeList.add(pickerValue);
notifyListeners();
}
}
example of UI layout in this app: there is a button that invokes timePicker
method.
I've added sample values to the list to make sure that problem there is in the adding the value, not in the fetching data from model class.
Previously I solved that by simply declaring that list in the StatefulWidget, but I've decided to use Provider package for better state management when app grows up.
class _GridWidgetState extends State<GridWidget> {
List timeList = [];
TimeOfDay _timeOfDay = TimeOfDay.now();
void _showTimePicker() {
showTimePicker(context: context, initialTime: TimeOfDay.now())
.then((value) {
setState(() {
_timeOfDay = value!;
timeList.add(value.format(context).toString());
});
});
}
...
Nevermind, I had to change
Provider.of<GridWidgetModel(context, listen:true)
tofalse
because it doesn't need to rebuild the widget tree when updating the list in this context.