Flutter:确保首先调用FirebaseApp.initializeApp(Context)

时间:2019-10-07 10:17:59

标签: flutter firebase-storage

我正在编写FLUTTER应用程序,并且试图将图像上传到Firebase存储上。这是我为重现错误而创建的简单测试应用。

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
import 'package:firebase_storage/firebase_storage.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File image;

  Future<File> getImageFileFromAssets(String path) async {
    final byteData = await rootBundle.load('assets/$path');

    final file = File('${(await getTemporaryDirectory()).path}/$path');
    await file.writeAsBytes(byteData.buffer
        .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

    return file;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 300,
              width: 450,
              child: image == null ? null : Image.file(image),
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () async {
                final fileName = 'imageName';
                final firebaseStorageRef =
                    FirebaseStorage.instance.ref().child('userFolder');
                final uploadTask =
                    firebaseStorageRef.child(fileName).putFile(image);
                await uploadTask.onComplete;
              },
            ),
            RaisedButton(
              child: Text('Load immagine'),
              onPressed: () async {
                image = await getImageFileFromAssets('test.jpg');
                setState(() {});
              },
            ),
          ],
        ),
      ),
    );
  }
}

如您所见,当我单击Load Image按钮时,我从资产中获取图像并将其存储在File对象中,并且效果很好。然后,当我想使用Submit按钮将该图像上传到Firebase的存储设备时,出现此错误:

E/MethodChannel#plugins.flutter.io/firebase_storage(19436): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.test_project. Make sure to call FirebaseApp.initializeApp(Context) first.
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@17.0.0:234)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at com.google.firebase.storage.FirebaseStorage.getInstance(com.google.firebase:firebase-storage@@17.0.0:86)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at io.flutter.plugins.firebase.storage.FirebaseStoragePlugin.onMethodCall(FirebaseStoragePlugin.java:57)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at android.app.ActivityThread.main(ActivityThread.java:6669)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/flutter (19436): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Default FirebaseApp is not initialized in this process com.example.test_project. Make sure to call FirebaseApp.initializeApp(Context) first., null)
E/flutter (19436): #0      StandardMethodCodec.decodeEnvelope 
package:flutter/…/services/message_codecs.dart:569
E/flutter (19436): #1      MethodChannel.invokeMethod 
package:flutter/…/services/platform_channel.dart:316
E/flutter (19436): <asynchronous suspension>
E/flutter (19436): #2      _StorageFileUploadTask._platformStart 
package:firebase_storage/src/upload_task.dart:130
E/flutter (19436): #3      StorageUploadTask._start 
package:firebase_storage/src/upload_task.dart:35
E/flutter (19436): <asynchronous suspension>
E/flutter (19436): #4      StorageReference.putFile 
package:firebase_storage/src/storage_reference.dart:65
E/flutter (19436): #5      _MyHomePageState.build.<anonymous closure> 
package:test_project/main.dart:60
E/flutter (19436): <asynchronous suspension>
E/flutter (19436): #6      _InkResponseState._handleTap 
package:flutter/…/material/ink_well.dart:654
E/flutter (19436): #7      _InkResponseState.build.<anonymous closure> 
package:flutter/…/material/ink_well.dart:729
E/flutter (19436): #8      GestureRecognizer.invokeCallback 
package:flutter/…/gestures/recognizer.dart:182
E/flutter (19436): #9      TapGestureRecognizer._checkUp 
package:flutter/…/gestures/tap.dart:365
E/flutter (19436): #10     TapGestureRecognizer.handlePrimaryPointer 
package:flutter/…/gestures/tap.dart:275
E/flutter (19436): #11     PrimaryPointerGestureRecognizer.handleEvent 
package:flutter/…/gestures/recognizer.dart:455
E/flutter (19436): #12     PointerRouter._dispatch 
package:flutter/…/gestures/pointer_router.dart:75
E/flutter (19436): #13     PointerRouter.route 
package:flutter/…/gestures/pointer_router.dart:102
E/flutter (19436): #14     GestureBinding.handleEvent 
package:flutter/…/gestures/binding.dart:218
E/flutter (19436): #15     GestureBinding.dispatchEvent 
package:flutter/…/gestures/binding.dart:198
E/flutter (19436): #16     GestureBinding._handlePointerEvent 
package:flutter/…/gestures/binding.dart:156
E/flutter (19436): #17     GestureBinding._flushPointerEventQueue 
package:flutter/…/gestures/binding.dart:102
E/flutter (19436): #18     GestureBinding._handlePointerDataPacket 
package:flutter/…/gestures/binding.dart:86
E/flutter (19436): #19     _rootRunUnary  (dart:async/zone.dart:1136:13)
E/flutter (19436): #20     _CustomZone.runUnary  (dart:async/zone.dart:1029:19)
E/flutter (19436): #21     _CustomZone.runUnaryGuarded  (dart:async/zone.dart:931:7)
E/flutter (19436): #22     _invoke1  (dart:ui/hooks.dart:263:10)
E/flutter (19436): #23     _dispatchPointerDataPacket  (dart:ui/hooks.dart:172:5)
E/flutter (19436):

数据库的规则是公共规则:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

有人可以告诉我我在做什么错吗?

5 个答案:

答案 0 :(得分:6)

根据文档,只需更改您的主要方法:

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

答案 1 :(得分:1)

所有Firebase版本均已更新,现在您必须在使用任何Firebase产品之前调用Firebase.initializeApp(),例如:

首先,所有Firebase产品现在都取决于firebase_core版本(0.5.0+),因此您需要将其添加到pubspec.yaml文件中:

dependencies:
  flutter:
    sdk: flutter
  firebase_core : ^0.5.0

然后您必须调用Firebase.initializeApp():

在main.dart中:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(); //Make sure you imported firebase_core
  runApp(MaterialApp(
    home: GettingStartedPage(),
  ));
}

答案 2 :(得分:0)

答案 3 :(得分:0)

对于谁来这里,我解决了这个问题。有很多事情要做,例如将您的应用程序添加到Firebase项目中并编辑一些文件。 唯一要做的是更好地阅读文档并遵循所有步骤: Add Firebase to your Flutter app

答案 4 :(得分:0)

import'package:firebase_core / firebase_core.dart';