【问题标题】:Access function defined in MyApp() class - FlutterMyApp() 类中定义的访问函数 - Flutter
【发布时间】:2021-09-15 11:38:14
【问题描述】:

我想从另一个类访问在我的顶级类中定义的函数。我该怎么做?

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 通知。

【问题讨论】:

    标签: flutter firebase-cloud-messaging


    【解决方案1】:

    您可以在不同的文件中定义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(); 
    }
    
    

    【讨论】:

    • 嗯,是的,我可以做到,但 FCM 实现不需要在顶级类中吗?
    • ` FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler); await notificationsPlugin.resolvePlatformSpecificImplementation() ?.createNotificationChannel(channelAndroid);`代码不是应该在顶级类吗?
    • 这个函数 FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler); 应该在你的 main 中(并且只调用一次),而 firebaseMessagingBackgroundHandler 应该是你的 main 中的顶级函数。那么await notificationsPlugin...可以在任意文件中定义。
    • await notificationsPlugin.resolvePlatformSpecificImplementation&lt;AndroidFlutterLocalNotificationsPlugin&gt;() ?.createNotificationChannel(channelAndroid); 你的意思是这个可以从任何地方调用?
    • 频道呢? const AndroidNotificationChannel channelAndroid = AndroidNotificationChannel( 'high_importance_channel', //id 'High Importance Notification', //name 'This channel is used for important notification', //description importance: Importance.high, sound: RawResourceAndroidNotificationSound('sound') ); 这个也需要在顶层还是可以在任何地方定义,然后在 main() 中调用
    猜你喜欢
    • 1970-01-01
    • 2020-02-11
    • 2020-05-27
    • 1970-01-01
    • 2012-06-24
    • 2014-08-05
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多