How to set Provider value from class field?


I am using Provider. I have got class. And I need to set value to Provider from field. But I do not have access to context here.

class _DateAndTimePickerDemoState extends State<DateAndTimePickerDemo> 
  DateTime _fromDate =;
  Provider.of<AppState>(context).selected_period = date; // here

How to set Provider value from class field?


You can get context in two ways:

  • Inside initState by calling Future.delayed(,() {... context ...})
  • After build method has been called Widget build(BuildContext context) {...}

In your case, I would call Provider.of<AppState>(context).selected_period = date; after build method, because most of the functions I define inside build method anyways so I can easily access context.

Answered By – Mārtiņš Ciekurs

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *