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
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
I'm building an app with firebase with push notifications so the app was running but after I used "flutter clean" this error appears without changing and piece of code
E/flutter (14812): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter (14812): #0 MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:180:53)
E/flutter (14812): #1 FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:102:16)
E/flutter (14812): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:73:31)
E/flutter (14812): #3 main (package:mitaa/main.dart:37:21)
the error appears in the package firebase_messaging: ^11.2.6
https://firebase.flutter.dev/docs/messaging/usage/
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
Blockquote
I'm trying to make google login with flutter app, and I got this error.
I've already get and put SHA-1 key to OAuth and Firebase and set google-services.json file under app directory.
But I still got same problem.
E/flutter (12401): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null)
E/flutter (12401): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (12401): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (12401): <asynchronous suspension>
E/flutter (12401): #2 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:356:43)
E/flutter (12401): <asynchronous suspension>
E/flutter (12401): #3 GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:235:30)
E/flutter (12401): <asynchronous suspension>
E/flutter (12401): #4 GoogleSignIn.signIn.isCanceled (package:google_sign_in/google_sign_in.dart)
E/flutter (12401): <asynchronous suspension>
E/flutter (12401):
This is how I set.
GCP OAuth
Firebase setting - I filled all blanks
and I don't know which clientId has to be on this area.
which clientId has to be on this area?
I got 4 clientId because I already used google clientId to make django web login with google
Step 1 :
Add this dependency into your pubsec file
firebase: ^9.0.2
firebase_core: ^1.2.1
firebase_database: ^7.1.0
firebase_auth: ^1.2.0
font_awesome_flutter: ^9.0.0
google_sign_in: ^5.0.3
Step : 2
Create a new dart file and paste this code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class FirebaseService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
Future<String?> signInwithGoogle() async {
try {
final GoogleSignInAccount? googleSignInAccount =
await _googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount!.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
await _auth.signInWithCredential(credential);
} on FirebaseAuthException catch (e) {
print(e.message);
throw e;
}
}
Future<void> signOutFromGoogle() async{
await _googleSignIn.signOut();
await _auth.signOut();
}
}
Step 3:
call sign in with google function:
Enable Google sign in Firebase
Add your SHA 1 key into Firebase Project
Compressed is coming out as null
File compressed = await FlutterImageCompress.compressAndGetFile(
img.path,
img.path.split('/').last,
quality: 80,
);
ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('postimages/${Path.basename(img.path)}');
await ref.putFile(compressed);
This is what the error I am getting
E/flutter (12851): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception:
NoSuchMethodError: The getter 'absolute' was called on null.
E/flutter (12851): Receiver: null
E/flutter (12851): Tried calling: absolute
E/flutter (12851): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (12851): #1 Reference.putFile
package:firebase_storage/src/reference.dart:126
E/flutter (12851): #2 _AddImageState.uploadFile
package:softclaw/…/addpost/addimage.dart:228
E/flutter (12851):
E/flutter (12851):
This will work perfectly fine
final imageUri = Uri.parse(img.path);
final String outputUri = imageUri.resolve('./output.webp').toString();
print(imageUri.toFilePath());
File compressed = await FlutterImageCompress.compressAndGetFile(
img.path, outputUri,
quality: 80, format: CompressFormat.webp);
print(img.path);
print(outputUri);
ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('postimages/${Path.basename(img.path)}');
await ref.putFile(compressed);
_imageName.add(await ref.getDownloadURL());
}
I tried to use the plugin https://pub.dev/packages/flutter_cache_manager_firebase to cache my audio that saved in firebase storage with the url of
https://firebasestorage.googleapis.com/v0/b/ocwa-app.appspot.com/o/142-1624205564448.aac?alt=media&token=b06a7cf9-5050-43ad-b5e9-60c4eda85b54
When I pass the url to the method
file = await FirebaseCacheManager().getSingleFile(widget.url);
and it throws an error in console
E/flutter (32343): [ERROR:flutter/shell/common/shell.cc(103)] Dart Unhandled Exception: [firebase_storage/unknown] location should not be a full URL., stack trace: #0 MethodChannelReference.getDownloadURL (package:firebase_storage_platform_interface/src/method_channel/method_channel_reference.dart:59:7)
E/flutter (32343): <asynchronous suspension>
E/flutter (32343): #1 FirebaseHttpFileService.get (package:flutter_cache_manager_firebase/src/firebase_http_file_service.dart:12:16)
E/flutter (32343): <asynchronous suspension>
E/flutter (32343): #2 WebHelper._updateFile (package:flutter_cache_manager/src/web/web_helper.dart:99:22)
E/flutter (32343): <asynchronous suspension>
E/flutter (32343): #3 WebHelper._downloadOrAddToQueue (package:flutter_cache_manager/src/web/web_helper.dart:67:7)
E/flutter (32343): <asynchronous suspension>
Please show me how to pass the correct url to the parameter. The current url I used is the downloadUrl return from
Future uploadAudio() async {
final uploadTimestamp = DateTime.now().millisecondsSinceEpoch;
setState(() {
fileName =
getImageFileName(G.loggedInId.toString(), '$uploadTimestamp');
fileName = fileName + '.aac';
});
Reference reference = FirebaseStorage.instance.ref().child(fileName);
TaskSnapshot uploading;
uploading = await reference.putFile(
File(recordingFile), SettableMetadata(contentType: 'audio/aac'));
return uploading.ref.getDownloadURL();
}
You need to remove the scheme from the URL.
You can do this like this:
final String url = widget.url;
final Uri uri = Uri.parse(url);
final urlWithoutScheme = url.replaceFirst('${uri.scheme}://', '');
///Pass it to the getSingleFile method
file = await FirebaseCacheManager().getSingleFile(urlWithoutScheme);
The code below is where the error is thrown from https://github.com/firebase/firebase-android-sdk/blob/master/firebase-storage/src/main/java/com/google/firebase/storage/FirebaseStorage.java.
if (lowerCaseLocation.startsWith("gs://")
|| lowerCaseLocation.startsWith("https://")
|| lowerCaseLocation.startsWith("http://")) {
throw new IllegalArgumentException("location should not be a full URL.");
Hello I tried to use firebase function by using Cloud_Functions Pkg but I got error in flutter consel , I tried to pass parameters in function which is UID of user .
Consel Error :
E/flutter (17871): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: [firebase_functions/internal] Response is not valid JSON object.
E/flutter (17871): #0 catchPlatformException
package:cloud_functions_platform_interface/…/utils/exception.dart:21
E/flutter (17871): #1 _rootRunBinary (dart:async/zone.dart:1378:47)
E/flutter (17871): #2 _CustomZone.runBinary (dart:async/zone.dart:1272:19)
E/flutter (17871): #3 _FutureListener.handleError (dart:async/future_impl.dart:166:20)
E/flutter (17871): #4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:716:47)
E/flutter (17871): #5 Future._propagateToListeners (dart:async/future_impl.dart:737:24)
E/flutter (17871): #6 Future._completeError (dart:async/future_impl.dart:547:5)
E/flutter (17871): #7 _completeOnAsyncError (dart:async-patch/async_patch.dart:264:13)
E/flutter (17871): #8 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart)
package:flutter/…/services/platform_channel.dart:1
E/flutter (17871): <asynchronous suspension>
Firebse Function :
exports.helloWorld = functions.https.onCall((data, context) => {
return data.data()['uid'];
});
Flutter run function from Firebase :
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
HttpsCallable callable =
FirebaseFunctions.instance.httpsCallable('listFruit');
final results = await callable.call(<String, dynamic>{
'uid': '123',
});
print(results
.data.toString()); // ["Apple", "Banana", "Cherry", "Date", "Fig", "Grapes"]
});
My goal :
pass parameters to firebase function .
I had the same error and it was due to the fact that the region was not provided, which seems to be required if the function is not deployed in us-central1. Following their documentation, you can perform the call like this:
FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('listFruit');
Instead of
exports.helloWorld = functions.https.onCall((data, context) => {
return data.data()['uid'];
});
you should do
exports.helloWorld = functions.https.onCall((data, context) => {
return data['uid']; // Or data.uid
});
Few more details in the Callable Cloud Functions doc.
In addition, note that your Cloud Function is named helloWorld but you call it with FirebaseFunctions.instance.httpsCallable('listFruit');. So you should adapt one or the other, e.g. FirebaseFunctions.instance.httpsCallable('helloWorld');