Search code examples
flutterdatetimedatepickerlocalizationlocale

showDatePicker 'No MaterialLocalizations found.' Just When I Use Locale


I am using showDatePicker and it works correctly, it's inside scaffold outside MaterialApp widget but just when I give it locale property it shows this error No MaterialLocalizations found. how can I solve it.

onPressed: () async {
                              String timeMsg = 'اختر التوقيت';
                              DateTime? _selectDate = await showDatePicker(
                                context: context,
                                locale: Locale('ar'),
                                initialDate: from
                                firstDate: first,
                                lastDate: new DateTime.now(),
                              );
}

Solution

  • Correct me if I got you wrong. Do you mean you are gonna call showDatePicker in a scaffold while this scaffold is not inside a MaterialApp?

    Generally, MaterialApp and CupertinoApp should be responsible for managing locales, check this page for more details. Context is used to locate every widget in the widget tree. In your DatePickerDialog, if it cannot find any ancestor widget to provide MaterialLocalizations for the given context, it will always raise this error.

    Afaik, place it inside a MaterialApp is the best choice. You can either place it in a new MaterialApp or just simply move your scaffold into the existing MaterialApp. The second one is always preferred as you won't enjoy dealing with multiple navigators when you are still learning how to use flutter.