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');
Related
This question already has an answer here:
The return type 'void' isn't assignable to 'FutureOr<T>', as required by 'Future.catchError'
(1 answer)
Closed 11 months ago.
I am trying to write a dart program which can register users and upon error print its description which i will eventually use in a Toast but it gives an error on catchError
User? _user = (await _auth.createUserWithEmailAndPassword(
email: email.toString(),
password: password.toString())
.catchError((e) {
print(e.message);
})).user;
I/flutter ( 3113): The email address is already in use by another account.
E/flutter ( 3113): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type
E/flutter ( 3113): #0 _FutureListener.handleError (dart:async/future_impl.dart:181:7)
E/flutter ( 3113): #1 Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47)
E/flutter ( 3113): #2 Future._propagateToListeners (dart:async/future_impl.dart:799:13)
E/flutter ( 3113): #3 Future._completeError (dart:async/future_impl.dart:574:5)
E/flutter ( 3113): #4 _completeOnAsyncError (dart:async-patch/async_patch.dart:287:13)
E/flutter ( 3113): #5 FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart)
E/flutter ( 3113):
E/flutter ( 3113):
Try wrapping it in a try...catch bloc it will throw FirebaseAuthException with a message field containing your message
https://firebase.flutter.dev/docs/auth/error-handling/
Split it up like so:
await _auth.createUserWithEmailAndPassword(
email: email.toString(),
password: password.toString(),
).catchError((e) {
print(e.message);
});
User? user = _auth.currentUser;
Hi developers, I am getting this issue
W/System ( 7624): Ignoring header X-Firebase-Locale because its value was null.
E/flutter ( 7624): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'FirebaseAuthException' is not a subtype of type 'String'
E/flutter ( 7624): #0 CubitApp.userRegestration.<anonymous closure> (package:shoping_app/lib/shared/cubit/appcubit.dart:172:29)
E/flutter ( 7624): #1 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 7624): #2 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 7624): #3 _FutureListener.handleError (dart:async/future_impl.dart:177:22)
E/flutter ( 7624): #4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47)
E/flutter ( 7624): #5 Future._propagateToListeners (dart:async/future_impl.dart:799:13)
E/flutter ( 7624): #6 Future._completeError (dart:async/future_impl.dart:609:5)
E/flutter ( 7624): #7 _completeOnAsyncError (dart:async-patch/async_patch.dart:272:13)
E/flutter ( 7624): #8 FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart)
E/flutter ( 7624): <asynchronous suspension>
on my flutter app when I was tried to create FirebaseAuth.instance.createUserWithEmailAndPassword
and this is the function that I wrote:
void create_Account({
required String firstName,
required String lastName,
required String userName,
required String address1,
required String address2,
required String phone,
required String email,
required String passWord,
}){
emit(RegisterLodingState());
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: passWord,
).then((value) {
emit(RegisterSuccessedState());
print(value.user!.email);
print(value.user!.uid);
}).catchError((err){
emit(RegisterErrorState(err));
print('Error when Login :$err');
});
and this code when I call the function:
ConditionalBuilder(
condition: true,
builder: (context) => defaultButton(
function: () {
if (formKey.currentState!.validate()) {
cubit.create_Account(
firstName:firstNameController.text,
lastName: lastNameController.text,
userName: userNameController.text,
address1:addressOneController.text,
address2:addressTwoController.text,
phone: phoneNumberController.text,
email: phoneNumberController.text,
passWord: passwordController.text,
);
}
},
text: 'Sign Up',
),
fallback: (context) => const Center(
child: CircularProgressIndicator()),
),
Note:
my emulator device is already connected with the internet and although I tried a physical device but the same problem.
You are trying to cast a FirebaseAuthException to a String which is incorrect so change this line:
print('Error when Login :$err');
to this:
print('Error when Login :${err.message}');
Also, take a look at this document to find out more about error handling in firebase.
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.
I'm developping an app using Flutter. And I want to execute some Firebase queries using Isolate.
But each time I run the app I get this error and nothing is displayed.
Here my code
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage>{
Isolate _isolate;
ReceivePort _receivePort;
String _data;
#override
Widget build(BuildContext context){
return WillPopScope(
child: Scaffold(){
child : Center(child:Text('${_data}'))
});
}
//To start
void _start() async {
_receivePort = ReceivePort();
_isolate = await Isolate.spawn(getData, _receivePort.sendPort);
_receivePort.listen(_displayData, onDone: () {
print("done!");
});
}
//Display data;
void _displayData(dynamic data) {
setState(() {
_data = data;
});
}
static void getData(SendPort sendPort) async{
var fire = Firestore.instance;
fire.settings(persistenceEnabled: true); //I get an error here
fire.document('MODEL/${id}')
.snapshots()
.listen((d) {//I get an error here
sendPort.send(d);
}
}
}
//I call the method _start in the initState
#override
void initState() {
_start();
super.initState();
}
Here is the error that I get
E/flutter (14817): [ERROR:flutter/runtime/dart_isolate.cc(808)] Unhandled exception:
E/flutter (14817): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
E/flutter (14817): #0 Window.sendPlatformMessage (dart:ui/window.dart:1133:9)
E/flutter (14817): #1 _DefaultBinaryMessenger._sendPlatformMessage (package:flutter/src/services/binary_messenger.dart:85:15)
E/flutter (14817): #2 _DefaultBinaryMessenger.send (package:flutter/src/services/binary_messenger.dart:129:12)
E/flutter (14817): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:309:51)
E/flutter (14817):
E/flutter (14817): #4 Query.snapshots. (package:cloud_firestore/src/query.dart:61:37)
E/flutter (14817): #5 _runGuarded (dart:async/stream_controller.dart:805:24)
E/flutter (14817): #6 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:213:7)
E/flutter (14817): #7 _ControllerStream._createSubscription (dart:async/stream_controller.dart:818:19)
E/flutter (14817):
E/flutter (14817): #4 Firestore.settings (package:cloud_firestore/src/firestore.dart:154:19)
E/flutter (14817):
E/flutter (14817): #5 HomePageState.getData (package:flutter_app/HelpFile/HomePage.dart:207:10)
E/flutter (14817): #8 _StreamImpl.listen (dart:async/stream_impl.dart:472:9)
E/flutter (14817): #9 HomePageState.getData (package:flutter_app/HomePage.dart:201:10)
E/flutter (14817):
E/flutter (14817): #10 _startIsolate. (dart:isolate-patch/isolate_patch.dart:308:17)
E/flutter (14817): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
Check this link https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseApp
Any FirebaseApp initialization must occur only in the main process of the app. Use of Firebase in processes other than the main process is not supported and will likely cause problems related to resource contention.
So far in my app everything is working except that one error I keep getting:
type 'String' is not a subtype of type 'File'
I tried many ways to try and fix the Issue but nothing has yet been resolved.
I can understand where the issue is, but I'm unable to fix it with countless attempts.
The problem is that im passing an Image using ImagePicker gallery im passing that image data to firebase as image: image.toString() and it works fine. Firebase takes the path but as an error i get: _file != null since the image is indeed a File image I cant fetch the data from firebase and pass the string path as an argument. therefore getting this error type 'String' is not a subtype of type 'File'. I display the image on the app like the following Image.file(image) Since its the only way to display a File image and use the ImagePicker. Is there a solution for this? or is it a bad way of doing the idea im trying to achieve?
here is the code:
image picker:
String img;
static Future<String> fileToB64(File f) async {
List<int> imageBytes = f.readAsBytesSync();
return base64Encode(
imageBytes,
);
}
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
setState(() {
data.image = imageFile;
});
fileToB64(imageFile).then((d) {
setState(() {
img = d; //base64Decode(d);
});
});
}
the provider:
import: 'dart:io';
class AddCar {
// other data
File image;
AddCar({
this.// other data
this.image,
});
}
firebase data:
Future<void> fetchAndSetCars() async {
const url = 'https://mylink.firebaseio.com/cars.json';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<AddCar> loadedCars = [];
extractedData.forEach((carId, carData) {
loadedCars.add(AddCar(
// other data
image: carData['image'],
));
});
_cars = loadedCars;
notifyListeners();
} catch (error) {
throw (error);
}
}
AddCar findById(String id) {
return _cars.firstWhere((carProd) => carProd.id == id);
}
void addCar(AddCar car) {
const url = 'https://mylink.firebaseio.com/cars.json';
http.post(
url,
body: json.encode({
// other data
'image': car.image.toString(),
}),
);
final newCar = AddCar(
// other data
image: car.image,
);
_cars.insert(0, newCar); // add car at the top of the list
notifyListeners();
}
how im displaying the fetch data from firebase:
#override
void initState() {
Future.delayed(Duration.zero).then((_) {
Provider.of<Cars>(context).fetchAndSetCars();
});
super.initState();
}
how im calling the data to be displayed in the app:
Container(
width: MediaQuery.of(context).size.width * 0.35,
height: MediaQuery.of(context).size.width * 0.35,
child: GestureDetector(
child: Image.file(
image,
fit: BoxFit.fill,
),
onTap: () {
Navigator.of(context).pushNamed(
MyCarDetails.routeName,
arguments: id,
);
},
),
),
What I get when I run the app:
Restarted application in 6,085ms.
E/flutter ( 3497): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'String' is not a subtype of type 'File'
E/flutter ( 3497): #0 Cars.fetchAndSetCars
package:flutter_app/providers/car_provider.dart:54
E/flutter ( 3497): <asynchronous suspension>
E/flutter ( 3497): #1 _CarAreaState.initState.<anonymous closure>
package:flutter_app/home_parts/cars_area.dart:28
E/flutter ( 3497): #2 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 3497): #3 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 3497): #4 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 3497): #5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter ( 3497): #6 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter ( 3497): #7 Future._complete (dart:async/future_impl.dart:512:7)
E/flutter ( 3497): #9 _rootRun (dart:async/zone.dart:1120:38)
E/flutter ( 3497): #10 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 3497): #11 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter ( 3497): #12 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter ( 3497): #13 _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 3497): #14 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 3497): #15 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:947:23)
E/flutter ( 3497): #16 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:21:15)
E/flutter ( 3497): #17 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
E/flutter ( 3497): #18 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
E/flutter ( 3497): #19 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
It seems that instead of doing this:
image: carData['image']
You should do this:
image: File(carData['image'])
Because carData['image'] is a String, not a File, and AddCar expects a File.
sometimes it's because of using ! null safety you should run like flutter run --no-sound-null-safety