I am getting this error message from timepicker in my flutter app:
Don't use 'BuildContext's across async gaps. Try rewriting the code to not reference the 'BuildContext'.
Here is the code I am using:
if (selectedDay != null) {
timeOfDay = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(
now.add(
const Duration(minutes: 1),
),
),
builder: (BuildContext context, Widget? child) {
return Theme(
data: ThemeData(
colorScheme: const ColorScheme.light(
primary: Colors.teal,
),
),
child: child!,
);
});
if (timeOfDay != null) {
return NotificationWeekAndTime(
dayOfTheWeek: selectedDay!, timeOfDay: timeOfDay);
}
}
I have tried to add if (!mounted) return; but the error doesn't disappear. Does anyone know what I can do to solve it?
To get rid of the warning, you may want to wrap the code in if block
(following the doc at https://api.flutter.dev/flutter/widgets/BuildContext/mounted.html):
if(context.mounted){
timeOfDay = await showDateTimePicker()
/// code continuation
}