首页 > 解决方案 > MyApp() 类中定义的访问函数 - Flutter

问题描述

我想从另一个类访问在我的顶级类中定义的函数。我怎样才能做到这一点 ?

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}


class MyApp extends StatefulWidget {

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> 
{
  
  void startListeningNotifications()
  {
    //start listening to fcm messages
  }


  void initState()
  {
    super.initState();
    
    startListeningNotifications(); 
  }  
}

我想从另一个类调用这个函数startListeningNotifications() 。那可能吗 ?

我已经在initState()中调用了这个函数,但是在某些情况下我需要从其他类中调用它。例如,如果用户尚未在您的 Firebase 应用中注册,那么在注册过程之后,我需要访问此方法才能开始收听 fcm 通知。

标签: flutterfirebase-cloud-messaging

解决方案


您可以startListeningNotifications()在不同的文件中定义,将其导入您需要的任何页面并在那里调用它。

// create lib/_utils/fcm_utils.dart
void startListeningNotifications() {
  // your function
}
...



// main.dart or any page you want to call your functions from
// TODO: replace yourAppName below with your app name
import 'package:yourAppName/_utils/fcm_utils.dart';
...
void initState() {
  super.initState();

  startListeningNotifications(); 
}


推荐阅读