flutter - 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 通知。
解决方案
您可以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();
}
推荐阅读
- r - How can I replace all instances of words with numbers in an R dataframe?
- javascript - 使用promise使用fileReader进行角度多图像预览
- hook-woocommerce - woocommerce set_manage_stock 在 woocommerce_process_product_meta 操作中不起作用
- tensorflow - 无法将 feed_dict 键解释为张量:张量不是此图的元素
- python - aiohttp 服务器无法下载大小超过某个阈值的文件
- javascript - 直播播放器中的自定义错误消息
- microsoft-graph-api - 从 MS Graph API 获取新的聊天消息
- google-bigquery - 从 BigQuery 表中提取人员和域并创建一个新表
- javascript - Google Firebase - Firestore - 纯 javascript - db.collection.update() 最初在浏览器刷新之前复制列表项,为什么?
- next.js - 在 Next.js 中使用环境变量时遇到问题