I want to call the _setSilentMode() function inside fireAlarm(). _setSilentMode() is inside statefull widget but fireAlarm() is outside stateful widget. whenever i put _setSilentMode() function inside fireAlarm() it gives error.
class _MyAppState extends State<MyApp> {
Future<void> _setSilentMode() async {
RingerModeStatus status;
try {
status = await SoundMode.setSoundMode(RingerModeStatus.silent);
setState(() {
_soundMode = status;
});
} on PlatformException {
print('Do Not Disturb access permissions required!');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: SingleChildScrollView(
child: Column(
children: [
Switch(
onChanged: (value) {
setState(() {
isOn = value;
});
AndroidAlarmManager.oneShot(
Duration(seconds: 15),
alarmId,
fireAlarm,
);
print('Alarm set at ${DateTime.now()}');
},
value: isOn,
activeColor: Colors.blue,
activeTrackColor: Colors.yellow,
inactiveThumbColor: Colors.redAccent,
inactiveTrackColor: Colors.orange,
)
],
))),
);
}
}
void fireAlarm() {
print('Alarm Fired at ${DateTime.now()}');
// i want to call _setSilentMode() here but it gives me error
_setSilentMode();
}
please help me that how to solve this problem and add _setSilentMode() inside fireAlarm() to work.
CodePudding user response:
- You can use GlobalKey to access the State and call method of state to update UI. You need to make state and method public.
- Alternatively, I recommend using state management libraries such as RiverPod or Provider.
CodePudding user response:
The method is outside the State class. For such you simply add widget before calling it
widget.fireAlarm
