简体   繁体   English

如何在 function 外部的有状态小部件内部调用 flutter function?

[英]how to call flutter function that is inside stateful widget in outside function?

I want to call the _setSilentMode() function inside fireAlarm().我想在 fireAlarm() 中调用 _setSilentMode() function。 _setSilentMode() is inside statefull widget but fireAlarm() is outside stateful widget. _setSilentMode() 在有状态小部件内,但 fireAlarm() 在有状态小部件外。 whenever i put _setSilentMode() function inside fireAlarm() it gives error.每当我将 _setSilentMode() function 放入 fireAlarm() 时,它都会出错。

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.请帮助我如何解决这个问题并在 fireAlarm() 中添加 _setSilentMode() 才能工作。

  • You can use GlobalKey to access the State and call method of state to update UI.您可以使用 GlobalKey 访问 State 并调用 state 的方法来更新 UI。 You need to make state and method public.您需要公开 state 和方法。
  • Alternatively, I recommend using state management libraries such as RiverPod or Provider.或者,我建议使用 state 管理库,例如 RiverPod 或 Provider。

The method is outside the State class.方法在State class之外。 For such you simply add widget before calling it为此,您只需在调用它之前添加小部件

widget.fireAlarm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM