NoSuchMethodError: The method 'ref' was called on null

Viewed 159

there I want help, I was creating my app with flutter and firebase, there, I want to upload images to firebase storage. so my file

import 'package:firebase_storage/firebase_storage.dart';

 uploadTOFirebase() async {
    final ref = FirebaseStorage.instance.ref('posts/post_$postId.jpg');
    await ref.putFile(image).whenComplete(() async {
      final url = await ref.getDownloadURL();
      setState(() {
        postlink = url;
      });
      // print(postlink);
    });
  }

but that saw me that error

E/flutter (19469): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'ref' was called on null.
E/flutter (19469): Receiver: null
E/flutter (19469): Tried calling: ref("posts/post_27cfad88-62bb-4211-9e5b-0c6d1e9029be.jpg")
E/flutter (19469): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (19469): #1      _UploadState.uploadTOFirebase (package:instaclone/pages/upload.dart:230:48)
E/flutter (19469): #2      _UploadState.HandleSubmit (package:instaclone/pages/upload.dart:226:11)
E/flutter (19469): <asynchronous suspension>
E/flutter (19469):

and I'm using flutter in andoird

3 Answers

Try using it like this.

final ref = FirebaseStorage.instance.ref().child("posts/post_$postId.jpg");

Did you call Firebase.initializeApp() anywhere? Without that, the Firebase SDKs won't be able to find your project on Google's servers.

See initializing FlutterFire in the FlutterFire docs for an example of how to do this.

uploadTOFirebase() async {
    UploadTask storageUploadTask = FirebaseStorage.instance.putFile('posts/post_$postId.jpg');
    TaskSnapshot storageTaskSnapshot =
        await storageUploadTask.whenComplete(() => null);
    String url = await storageTaskSnapshot.ref.getDownloadURL();
    setState((){postlink = url;});
  }

Try this code. Did some small changes.

Related