从 Flutter 中的资源加载 FirebaseOptions 时出现 PlatformException

问题描述 投票:0回答:1

我正在开发一个与 Firebase 集成的 Flutter 项目,并且遇到了我正在努力解决的 PlatformException。当应用尝试从资源加载 FirebaseOptions 时,会引发异常。这是错误消息:

发生异常。

PlatformException (PlatformException(java.lang.Exception: Failed to load FirebaseOptions from resource. Check that you have defined values.xml correctly., Exception, Cause: null, Stacktrace: java.lang.Exception: Failed to load FirebaseOptions from resource. Check that you have defined values.xml correctly.
    at io.flutter.plugins.firebase.core.FlutterFirebaseCorePlugin.lambda$optionsFromResource$4$io-flutter-plugins-firebase-core-FlutterFirebaseCorePlugin(FlutterFirebaseCorePlugin.java:207)
    at io.flutter.plugins.firebase.core.FlutterFirebaseCorePlugin$$ExternalSyntheticLambda2.run(Unknown Source:4)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:644)
    at java.lang.Thread.run(Thread.java:1012)
, null))

我找不到

values.xml
。我还确保在任何其他 Firebase 相关操作之前调用
Firebase.initializeApp()

这是我迄今为止尝试过的:

确保values.xml文件正确放置在android/app/src/main/res/values目录中。 更新 pubspec.yaml 中的所有 Firebase 依赖项。 运行 flutter clean 和 flutter pub get 来清除任何潜在的构建问题。 在模拟器和真实设备上测试应用程序。

android flutter
1个回答
0
投票

确保您有此文件:

还将其添加到 pubspec.yaml 文件中的资产中。

project_application\android\app\google-services.json

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Load the google-services.json file as a string
  String googleServicesJsonString =
      await rootBundle.loadString('android\\app\\google-services.json');
  print("google_Services_Json_String: $googleServicesJsonString");

  // Parse the JSON String into a JSON
  final googleServicesJson = jsonDecode(googleServicesJsonString);
  final projectId = googleServicesJson['project_info']["project_id"];
  print("projectId: $projectId");
  final messagingSenderId =
      googleServicesJson['project_info']["project_number"];
  print("messagingSenderId: $messagingSenderId");
  final storageBucket = googleServicesJson['project_info']["storage_bucket"];
  print("storageBucket: $storageBucket");
  final appId =
      googleServicesJson['client'][0]["client_info"]["mobilesdk_app_id"];
  print("appId: $appId");
  final apiKey = googleServicesJson['client'][0]["api_key"][0]["current_key"];
  print("apiKey: $apiKey");

  // Create a FirebaseOptions object from the extracted configuration
  FirebaseOptions options = FirebaseOptions(
    apiKey: apiKey,
    appId: appId,
    messagingSenderId: messagingSenderId,
    projectId: projectId,
    storageBucket: storageBucket,
  );

  // Initialize Firebase with the options
  await Firebase.initializeApp(options: options);

  // Log or print a message here to verify initialization
  print('Firebase app is initialized!');

  runApp(MyApp());
}

如果需要,可以删除打印语句。

© www.soinside.com 2019 - 2024. All rights reserved.