Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Make sure to call FirebaseApp.initializeApp(Context) first

I am writing a FLUTTER application and I am trying to upload an image on the Firebase storage. This is a simple test app I've created to reproduce the error.

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(() {});
              },
            ),
          ],
        ),
      ),
    );
  }
}

As you can see when I click on the Load Image button I take an image from the assets and I store it in a File object, and it works fine. Then when I want to upload that image on Firebase's storage using the Submit button I get this error:

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):

Database's rules are the public ones:

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

Can someone tell me what am I doing wrong?

like image 227
AlessioF Avatar asked Oct 07 '19 10:10

AlessioF


3 Answers

According to docs just change your main method:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
like image 141
Twin322 Avatar answered Oct 27 '22 13:10

Twin322


For who come here, I solved the problem. There is a lot of stuff to do, such as add your app to your Firebase project and edit some files. The only thing to do is to read better the docs and follow all the steps: Add Firebase to your Flutter app

like image 5
AlessioF Avatar answered Oct 27 '22 13:10

AlessioF


All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example:

First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  firebase_core : ^0.5.0

Then you have to call Firebase.initializeApp():

In the main.dart:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(); //Make sure you imported firebase_core
  runApp(MaterialApp(
    home: GettingStartedPage(),
  ));
}
like image 1
Brian Kavishe Avatar answered Oct 27 '22 14:10

Brian Kavishe