I wanted to change the package name of my project so I changed the applicationId in build.gradle and in android.xml.
I changed package name using below guide
https://medium.com/#skyblazar.cc/how-to-change-the-package-name-of-your-flutter-app-4529e6e6e6fc
Firebase database was linked with my project so I thought I had to change the package name in Firebase too. So, I added new app in Firebase with UPDATED package name of the project and added SHA key as required. After doing all this I started to test my app. Everything is working fine except phone authentication. Google authentication is working fine.
I don't know why, while phone authentication, I get below error and app get crashed. Build in function FirebaseAuth.instance.verifyPhoneNumber never executed. I'm wondering why?
Error before termination of the app
I/flutter (15570): New user result at the end before await: null
E/zzf (15570): Problem retrieving SafetyNet Token: 7:
W/ActivityThread(15570): handleWindowVisibility: no activity for token android.os.BinderProxy#7518a38
D/ViewRootImpl#9a0d0b4[MainActivity](15570): MSG_WINDOW_FOCUS_CHANGED 0 1
D/InputMethodManager(15570): prepareNavigationBarInfo() DecorView#b62e3fa[MainActivity]
D/InputMethodManager(15570): getNavigationBarColor() -855310
I/DecorView(15570): createDecorCaptionView >> DecorView#1ec25a[], isFloating: false, isApplication: true, hasWindowDecorCaption: false, hasWindowControllerCallback: true
W/System (15570): Ignoring header X-Firebase-Locale because its value was null.
I/System.out(15570): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(15570): (HTTPLog)-Static: isSBSettingEnabled false
D/InputTransport(15570): Input channel constructed: fd=97
D/ViewRootImpl#141d474[RecaptchaActivity](15570): setView = DecorView#1ec25a[RecaptchaActivity] TM=true MM=false
D/ViewRootImpl#141d474[RecaptchaActivity](15570): dispatchAttachedToWindow
D/ViewRootImpl#141d474[RecaptchaActivity](15570): Relayout returned: old=[0,0][1080,2220] new=[0,0][1080,2220] result=0x7 surface={valid=true 545211748352} changed=true
D/OpenGLRenderer(15570): eglCreateWindowSurface = 0x7efbe16f80, 0x7ef1271010
D/ViewRootImpl#141d474[RecaptchaActivity](15570): MSG_RESIZED: frame=Rect(0, 0 - 1080, 2220) ci=Rect(0, 63 - 0, 0) vi=Rect(0, 63 - 0, 0) or=1
D/InputTransport(15570): Input channel destroyed: fd=132
D/AndroidRuntime(15570): Shutting down VM
E/AndroidRuntime(15570): FATAL EXCEPTION: main
E/AndroidRuntime(15570): Process: com.xxxxx.xxxxx, PID: 15570
E/AndroidRuntime(15570): java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/browser/customtabs/CustomTabsIntent$Builder;
E/AndroidRuntime(15570): at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth##20.0.1:13)
E/AndroidRuntime(15570): at com.google.android.gms.internal.firebase-auth-api.zzth.zzb(com.google.firebase:firebase-auth##20.0.1:7)
E/AndroidRuntime(15570): at com.google.android.gms.internal.firebase-auth-api.zzth.onPostExecute(Unknown Source:2)
E/AndroidRuntime(15570): at android.os.AsyncTask.finish(AsyncTask.java:695)
E/AndroidRuntime(15570): at android.os.AsyncTask.access$600(AsyncTask.java:180)
E/AndroidRuntime(15570): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
E/AndroidRuntime(15570): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(15570): at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime(15570): at android.app.ActivityThread.main(ActivityThread.java:7073)
E/AndroidRuntime(15570): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(15570): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/AndroidRuntime(15570): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
E/AndroidRuntime(15570): Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.browser.customtabs.CustomTabsIntent$Builder" on path: DexPathList[[zip file "/data/app/com.storeifie.storeify-DOxHXgyJA9JAe6BK8YeeWA==/base.apk"],nativeLibraryDirectories=[/data/app/com.storeifie.storeify-DOxHXgyJA9JAe6BK8YeeWA==/lib/arm64, /data/app/com.storeifie.storeify-DOxHXgyJA9JAe6BK8YeeWA==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
E/AndroidRuntime(15570): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
E/AndroidRuntime(15570): at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/AndroidRuntime(15570): at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(15570): ... 12 more
I/Process (15570): Sending signal. PID: 15570 SIG: 9
Lost connection to device.
Exited (sigterm)
Below is the code snippet of verifyPhone function.
In below code snippet await FirebaseAuth.instance.verifyPhoneNumber never ran.
verificationComplete and smsCodeSent never got executed. I'm wondering why? It was working fine before changing package name
Future<dynamic> verifyPhone(phoneNo, BuildContext context) async {
var completer = Completer<dynamic>();
dynamic newUserResult;
Future<String> getOTPresult() async {
print("Dialog shown");
await showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (context) => Container(
height: 270,
child: OTPBottomSheet(controller: _otpController),
),
);
return _otpController.text;
}
// >>>>>>>>>>>>> On Complete
final PhoneVerificationCompleted verificationComplete =
(AuthCredential authCred) async {
print(" I N S I D E C O M P L E T E ");
newUserResult = await signInWithPhoneNumber(authCred);
completer.complete(newUserResult);
};
// >>>>>>>>>>>>> On Timeout
final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verID) {
print("\n2. Auto retrieval time out");
completer.complete(newUserResult);
};
// >>>>>>>>>>>>> On manual code verification
final PhoneCodeSent smsCodeSent =
(String verID, [int forceCodeResend]) async {
print(" I N S I D E C O D E S E N T");
var OTPDialogResult = await getOTPresult();
if (OTPDialogResult != null) {
AuthCredential authCred = PhoneAuthProvider.credential(
verificationId: verID, smsCode: OTPDialogResult);
newUserResult = AuthService().signInWithPhoneNumber(authCred);
if (!completer.isCompleted) {
completer.complete(newUserResult);
}
}
};
// >>>>>>>>>>>>> On Ver failed
final PhoneVerificationFailed verificationFailed =
(Exception authException) {
completer.complete(newUserResult);
};
await FirebaseAuth.instance
.verifyPhoneNumber(
phoneNumber: phoneNo,
timeout: Duration(seconds: 50),
verificationCompleted: verificationComplete,
verificationFailed: verificationFailed,
codeSent: smsCodeSent,
codeAutoRetrievalTimeout: autoRetrieve,
).catchError((error) {
print(error.toString());
});
print("New user result at the end before await: " + newUserResult.toString());
newUserResult = await completer.future;
print("New user result at the end after await: " + newUserResult.toString());
return newUserResult;
}
signInWithPhoneNumber function
Future signInWithPhoneNumber(AuthCredential authCreds) async {
try {
UserCredential result = await FirebaseAuth.instance.signInWithCredential(authCreds);
User customUser = result.user;
return _userFormFirebaseUser(customUser).getuid;
}
CustData _userFormFirebaseUser(User user) {
print("----> Inside _userFormFirebaseUser and user ID: " + user.uid);
return user != null
? CustData(
custId: user.uid,
)
: null;
}
// --- CustData model class
class CustData {
String custId;
String custName;
String custPhNo;
String custContactNO;
DateTime custDateOfBirth;
Map<String, dynamic> address;
String cartID;
CustData({
this.custId,
this.custName,
this.custPhNo,
this.custDateOfBirth,
this.address,
this.cartID,
this.custContactNO,
});
CustData.initial() : custId = '';
String get getuid => this.custId;
}
I solved the problem by simply adding below line into app/build.gradle dependencies.
implementation "androidx.browser:browser:1.2.0"
Related
Today i updated the android emulator i use frecuently and for some reason im getting this error. I already update all possible dependences and packages.
I/FirebaseAuth(11346): [FirebaseAuth:] Preparing to create service connection to fallback implementation
W/System (11346): Ignoring header X-Firebase-Locale because its value was null.
E/flutter (11346): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The getter 'user' was called on null.
E/flutter (11346): Receiver: null
E/flutter (11346): Tried calling: user
E/flutter (11346): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (11346): #1 _RegistrarseState.signupNewUser (package:mundoplay/code/registrarse/registrarse.dart:511:9)
E/flutter (11346): <asynchronous suspension>
This is part of my current code for the user to register:
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
void signupNewUser(BuildContext context) async {
showDialog(context: context,
barrierDismissible: false,
builder: (BuildContext context)
{
return barraProgreso(mensaje: "Creando su cuenta, espere...",);
});
final firebaseUser = (await _firebaseAuth
.createUserWithEmailAndPassword(
email: email.text, password: password.text)
.catchError((errMsg) {
Navigator.pop(context);
setState(() {
_error = Errors.show(errMsg.code);
});
})).user;
if (firebaseUser != null)
{
Map userDataMap = {
"nombre": nombre.text.trim(),
"apellido": apellido.text.trim(),
"email": email.text.trim(),
"password": password.text.trim(),
"celular": celular.text.trim(),
"direccion": direccion.text.trim(),
"localidad": localidad.text.trim(),
};
usersRef.child(firebaseUser.uid).set(userDataMap).then((value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', email.text);
//Navigator.push(context, new MaterialPageRoute(builder: (context) => new SeleccionarConsola()));
});
My register and login works with a form with TextEditingControllers that are set to the controller value.
I'm working with the firebase realtime database... any extra info, just ask me and i will try add it. THANKS!
According to the docs, catchError
Returns a new Future that will be completed with either the result of this future or the result of calling the onError callback.
So when you initialize your firebaseUser, you use a catchError that doesn't return nothing (i.e. implicitely returns null). You can see this in practice with a simple example:
Future<T> handleError<T>(Future<T> future) {
return future.catchError((e) {
print("An error occurred.");
// Not returning anything here!
});
}
void main() async {
// When no error occurs, it will print 1
print(await handleError(Future.value(1)));
// When an error occurs, it will print null
print(await handleError(Future.error(Error())));
}
Since you've already said that you're not connected to the internet since you're using an emulator, an error is being thrown inside the future (maybe a "no internet exception" kind of error), the future is returning null and thus the "The getter 'user' was called on null." message.
There are two ways you can avoid this:
Using the ?. operator:
final firebaseUser = (await _firebaseAuth
.createUserWithEmailAndPassword(
email: email.text, password: password.text)
.catchError((errMsg) {
Navigator.pop(context);
setState(() {
_error = Errors.show(errMsg.code);
});
}))?.user; // <- use it here!
Doing it step-by-step:
final result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email.text,
password: password.text,
).catchError((e) {
Navigator.pop(context);
setState(() => _error = Errors.show(errMsg.code));
});
// Early exit
if (result == null) return;
// Only retrieve the firebase user here
final firebaseUser = result.user;
This question already has an answer here:
Generate Flutter Local Notification when background FCM Triggers
(1 answer)
Closed 1 year ago.
I am trying to use Firebase messaging in Flutter app. Somewhere I am missing something so I am facing with errors...
My notification_handler code;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> myBackgroundMessageHandler(Map<String, dynamic> message) {
if (message.containsKey('data')) {
// Handle data message
NotificationHandler.showNotification(message);
}
return Future<void>.value();
}
class NotificationHandler {
FirebaseMessaging _fcm = FirebaseMessaging();
static final NotificationHandler _singleton = NotificationHandler._internal();
factory NotificationHandler() {
return _singleton;
}
NotificationHandler._internal();
BuildContext myContext;
initializeFCMNotification(BuildContext context) async {
myContext = context;
var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification);
_fcm.onTokenRefresh.listen((newToken) async {
User _currentUser = FirebaseAuth.instance.currentUser;
await FirebaseFirestore.instance.doc("tokens/" + _currentUser.uid).set({"token": newToken});
});
_fcm.configure(
onMessage: (Map<String, dynamic> message) async {
//print("onMessage tetiklendi: $message");
showNotification(message);
},
onBackgroundMessage: myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
//print("onLaunch tetiklendi: $message");
},
onResume: (Map<String, dynamic> message) async {
// print("onResume tetiklendi: $message");
},
);
}
static void showNotification(Map<String, dynamic> message) async {
var mesaj = Person(
name: message["data"]["title"],
key: '1',
//icon: userURLPath,
icon: DrawableResourceAndroidIcon('daisy'),
);
var mesajStyle = MessagingStyleInformation(mesaj, messages: [Message(message["data"]["message"], DateTime.now(), mesaj)]);
var androidPlatformChannelSpecifics = AndroidNotificationDetails('1234', 'Yeni Mesaj', 'your channel description',
styleInformation: mesajStyle, importance: Importance.max, priority: Priority.high, ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.showDailyAtTime(
1,
message["data"]["title"],
"Dont Forget to Set Your Weight in Today**",
Time(20,44,0),
platformChannelSpecifics,
);
print("handler succesful");
}
Future onSelectNotification(String payload) async {
final _userModel = Provider.of<UserModel>(myContext);
if (payload != null) {
// debugPrint('notification payload: ' + payload);
Map<String, dynamic> gelenBildirim = await jsonDecode(payload);
}
}
Future onDidReceiveLocalNotification(int id, String title, String body, String payload) {}
}
Instead of notification, I gets that below error and the app shut downs.
PID: 21082
E/AndroidRuntime(21082): java.lang.RuntimeException: Unable to start receiver com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/AndroidRuntime(21082): at android.app.ActivityThread.handleReceiver(ActivityThread.java:3259)
E/AndroidRuntime(21082): at android.app.ActivityThread.-wrap17(Unknown Source:0)
E/AndroidRuntime(21082): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1677)
E/AndroidRuntime(21082): at android.os.Handler.dispatchMessage(Handler.java:105)
E/AndroidRuntime(21082): at android.os.Looper.loop(Looper.java:164)
E/AndroidRuntime(21082): at android.app.ActivityThread.main(ActivityThread.java:6541)
E/AndroidRuntime(21082): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(21082): at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
E/AndroidRuntime(21082): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
E/AndroidRuntime(21082): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/AndroidRuntime(21082): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:237)
E/AndroidRuntime(21082): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:179)
E/AndroidRuntime(21082): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:791)
E/AndroidRuntime(21082): at com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver.onReceive(ScheduledNotificationReceiver.java:46)
E/AndroidRuntime(21082): at android.app.ActivityThread.handleReceiver(ActivityThread.java:3252)
E/AndroidRuntime(21082): ... 8 more
F/crash_dump64(25605): crash_dump.cpp:235] target died before we could attach (received main tid = 25603)
Lost connection to device.
I noticed that there were questions asked about this error before And solved the problem. Here is the link;
Generate Flutter Local Notification when background FCM Triggers
I solved this issue (App crashes upon phone authentication after changing package name - Flutter) of app crash by adding implementation "androidx.browser:browser:1.2.0" into app/build.gradle dependencies.
But NOW whole phone authentication procedure got changed. Now app open a browser to do Not a robot test. But I don't want app to open a browser just to verify it's not a robot it make entire process slow and ugly. Below is the video example. How to get rid of this issue? It shows app firebase address in the browser link too.
Video example of issue is below
https://drive.google.com/file/d/1G7noQWyyAHvyTo_Te0v6d2O3IvaiClAw/view?usp=sharing
Below is the code snippet of verifyPhone function.
Future<dynamic> verifyPhone(phoneNo, BuildContext context) async {
var completer = Completer<dynamic>();
dynamic newUserResult;
Future<String> getOTPresult() async {
print("Dialog shown");
await showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (context) => Container(
height: 270,
child: OTPBottomSheet(controller: _otpController),
),
);
return _otpController.text;
}
// >>>>>>>>>>>>> On Complete
final PhoneVerificationCompleted verificationComplete =
(AuthCredential authCred) async {
print(" I N S I D E C O M P L E T E ");
newUserResult = await signInWithPhoneNumber(authCred);
completer.complete(newUserResult);
};
// >>>>>>>>>>>>> On Timeout
final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verID) {
print("\n2. Auto retrieval time out");
completer.complete(newUserResult);
};
// >>>>>>>>>>>>> On manual code verification
final PhoneCodeSent smsCodeSent =
(String verID, [int forceCodeResend]) async {
print(" I N S I D E C O D E S E N T");
var OTPDialogResult = await getOTPresult();
if (OTPDialogResult != null) {
AuthCredential authCred = PhoneAuthProvider.credential(
verificationId: verID, smsCode: OTPDialogResult);
newUserResult = AuthService().signInWithPhoneNumber(authCred);
if (!completer.isCompleted) {
completer.complete(newUserResult);
}
}
};
// >>>>>>>>>>>>> On Ver failed
final PhoneVerificationFailed verificationFailed =
(Exception authException) {
completer.complete(newUserResult);
};
await FirebaseAuth.instance
.verifyPhoneNumber(
phoneNumber: phoneNo,
timeout: Duration(seconds: 50),
verificationCompleted: verificationComplete,
verificationFailed: verificationFailed,
codeSent: smsCodeSent,
codeAutoRetrievalTimeout: autoRetrieve,
).catchError((error) {
print(error.toString());
});
print("New user result at the end before await: " + newUserResult.toString());
newUserResult = await completer.future;
print("New user result at the end after await: " + newUserResult.toString());
return newUserResult;
}
signInWithPhoneNumber function
Future signInWithPhoneNumber(AuthCredential authCreds) async {
try {
UserCredential result = await FirebaseAuth.instance.signInWithCredential(authCreds);
User customUser = result.user;
return _userFormFirebaseUser(customUser).getuid;
}
CustData _userFormFirebaseUser(User user) {
print("----> Inside _userFormFirebaseUser and user ID: " + user.uid);
return user != null
? CustData(
custId: user.uid,
)
: null;
}
// --- CustData model class
class CustData {
String custId;
String custName;
String custPhNo;
String custContactNO;
DateTime custDateOfBirth;
Map<String, dynamic> address;
String cartID;
CustData({
this.custId,
this.custName,
this.custPhNo,
this.custDateOfBirth,
this.address,
this.cartID,
this.custContactNO,
});
CustData.initial() : custId = '';
String get getuid => this.custId;
}
Already making the whole procedure slow...
Try this Auth Version and it will work well for you :)
implementation com.google.firebase:firebase-auth:19.3.1
The reason behind this is explained in the official documentation https://firebase.google.com/docs/auth/android/phone-auth#enable-app-verification
reCAPTCHA verification: In the event that SafetyNet cannot be used, such as when the user does not have Google Play Services support, or when testing your app on an emulator, Firebase Authentication uses a reCAPTCHA verification to complete the phone sign-in flow. The reCAPTCHA challenge can often be completed without the user having to solve anything. Please note that this flow requires that a SHA-1 is associated with your application.
To solve it you have to :
In the Google Cloud Console, enable the Android DeviceCheck API for your project. The default Firebase API Key will be used, and needs to be allowed to access the DeviceCheck API.
If you haven't yet specified your app's SHA-256 fingerprint, do so from the Settings Page of the Firebase console. Refer to Authenticating Your Client for details on how to get your app's SHA-256 fingerprint.
Created a new class to manage sign-in methods in one place, a Dart class with no flutter Widget.
It gives errors about FIREBASE INITIALIZATION after following https://firebase.flutter.dev/docs/overview/#initializing-flutterfire.
Error: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp().
_firebaseAuth is useless without it.
Full sample project here: https://github.com/dashanan13/time_tracker_flutter_course.git
Please help, this is frustrating.
StackTrace:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
Parameter format not correct -
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Waiting for Android SDK built for x86 to report its views...
Debug service listening on ws://127.0.0.1:60201/mhWPMlMla50=/ws
Syncing files to device Android SDK built for x86...
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
W/AnalyticsUserIDStore(20120): initStore should have been called before calling setUserID
W/UserDataStore(20120): initStore should have been called before calling setUserID
D/EGL_emulation(20120): eglMakeCurrent: 0xd731a9c0: ver 2 0 (tinfo 0xd730f730)
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
I/OpenGLRenderer(20120): Davey! duration=2122ms; Flags=1, IntendedVsync=172506915033871, Vsync=172506948367203, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=172506964470903, AnimationStart=172506964518803, PerformTraversalsStart=172506964557703, DrawStart=172508239012703, SyncQueued=172508239844803, SyncStart=172508241475003, IssueDrawCommandsStart=172508241758403, SwapBuffers=172508678528903, FrameCompleted=172509039559203, DequeueBufferDuration=21745000, QueueBufferDuration=142000,
I/Choreographer(20120): Skipped 129 frames! The application may be doing too much work on its main thread.
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
I/asics_for_dars(20120): Background young concurrent copying GC freed 26775(1377KB) AllocSpace objects, 9(360KB) LOS objects, 41% free, 2468KB/4219KB, paused 131.474ms total 1.416s
D/EGL_emulation(20120): eglMakeCurrent: 0xea67f940: ver 2 0 (tinfo 0xd3e265e0)
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following FirebaseException was thrown building LandingPage(dirty, dependencies:
[InheritedProvider<AuthBase>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
LandingPage
file:///C:/Users/.../basics_for_darsh/lib/main.dart:68:41
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 Auth.onAuthStateChanged (package:basics_for_darsh/utilities/auth.dart:47:35)
#4 LandingPage.build (package:basics_for_darsh/utilities/landingPage.dart:18:22)
#5 StatelessElement.build (package:flutter/src/widgets/framework.dart:4620:28)
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
#7 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#8 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
#9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
... Normal element mounting (132 frames)
#141 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#142 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5991:32)
... Normal element mounting (287 frames)
#429 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#430 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
#431 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1174:16)
#432 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1145:5)
#433 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1087:17)
#434 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2620:19)
#435 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1086:13)
#436 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:927:7)
#437 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:908:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following FirebaseException was thrown building LandingPage(dirty, dependencies: [InheritedProvider<AuthBase>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
LandingPage file:///C:/Users/.../basics_for_darsh/lib/main.dart:68:41
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 Auth.onAuthStateChanged (package:basics_for_darsh/utilities/auth.dart:47:35)
#4 LandingPage.build (package:basics_for_darsh/utilities/landingPage.dart:18:22)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
Firebase authentication is useless without initialization.
Error: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
Please help.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:google_sign_in/google_sign_in.dart';
class MyUser {
MyUser({#required this.uid});
final String uid;
}
abstract class AuthBase {
Stream<MyUser> get onAuthStateChanged;
Future<MyUser> currentUser();
Future<MyUser> signInAnonymously();
Future<MyUser> signInWithGoogle();
Future<void> signOut();
}
class Auth implements AuthBase {
var _initialization,_firebaseAuth;
Auth(){
_intializeMe();
_firebaseAuth = FirebaseAuth.instance;
}
_intializeMe() async {
FirebaseApp _initialization = (await Firebase.initializeApp());
}
MyUser _userFromFirebase(User user) {
if (user == null) {
return null;
}
return MyUser(uid: user.uid);
}
#override
Stream<MyUser> get onAuthStateChanged {
return _firebaseAuth.authStateChanges().map(_userFromFirebase);
}
#override
Future<MyUser> currentUser() async {
final user = await _firebaseAuth.currentUser;
return _userFromFirebase(user);
}
#override
Future<MyUser> signInAnonymously() async {
final authResult = await _firebaseAuth.signInAnonymously();
return _userFromFirebase(authResult.user);
}
#override
Future<MyUser> signInWithGoogle() async {
final googleSignIn = GoogleSignIn();
final googleAccount = await googleSignIn.signIn();
if (googleAccount != null) {
final googleAuth = await googleAccount.authentication;
if (googleAuth.accessToken != null && googleAuth.idToken != null) {
final authResult = await _firebaseAuth.signInWithCredential(
GoogleAuthProvider.credential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
),
);
return _userFromFirebase(authResult.user);
} else {
throw PlatformException(
code: 'ERROR_MISSING_GOOGLE_AUTH_TOKEN',
message: 'Missing Google Auth Token',
);
}
} else {
throw PlatformException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user',
);
}
}
#override
Future<void> signOut() async {
final googleSignIn = GoogleSignIn();
await googleSignIn.signOut();
final facebookLogin = FacebookLogin();
await facebookLogin.logOut();
await _firebaseAuth.signOut();
}
}
Call for Auth() methods
import 'dart:async';
import 'package:basics_for_darsh/authentication/signin.dart';
import 'package:basics_for_darsh/screens/welcome_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'auth.dart';
class LandingPage extends StatelessWidget {
static const String id = 'landing_page';
#override
Widget build(BuildContext context) {
final auth = Provider.of<AuthBase>(context);
return StreamBuilder<MyUser>(
stream: auth.onAuthStateChanged,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
MyUser user = snapshot.data;
if (user == null) {
return AppSignIn();
}
return WelcomeScreen();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
});
}
}
initializeApp() is asynchronous, therefore do the following:
Auth(){
_intializeMe().then((_){
_firebaseAuth = FirebaseAuth.instance;
});
}
Future<void> _intializeMe() async {
return await Firebase.initializeApp();
}
Before accessing FirebaseAuth, you have to initialize Firebase. Therefore you can use then() which will register a callback that will be called when the future is done.
My Problem
Can Anyone Help I'm trying to send my images to firebase storage then retrieving the download URL and saving to the firebasefirestore. But my FirebaseStorage method isn't running.
Happening After firebase_storage: ^4.0.0 update
My FirebaseStorage().ref().child('path).putFile() method isn't running
FirebaseStorage()
.ref()
.child("Accounts Posts/Images/").putFile(//MyFIle);
Here's my Code
static final FirebaseStorage storage = FirebaseStorage.instance;
static final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<dynamic> sendData(SearchTileModel st, List<File> data) async {
bool completed = false;
CollectionReference _collec = _firestore.collection('Accounts Posts');
List<String> _imageUrls = [];
print(data.length);
data.length > 0
? data.asMap().forEach((
index,
element,
) async {
print(index);
print(element);
String downloadUrl;
/////// HERE this code doesn't get called up ////////////
StorageTaskSnapshot snapshot = await FirebaseStorage()
.ref()
.child("Accounts Posts/Images/${index}")
.putFile(element)
.onComplete
.then((value) {
downloadUrl = value.ref.getDownloadURL().toString();
return;
});
print(downloadUrl);
print(snapshot);
print(snapshot.error);
if (snapshot.error == null) {
await snapshot.ref
.getDownloadURL()
.then((value) => downloadUrl = value.toString());
print(downloadUrl);
_imageUrls.insert(index, downloadUrl);
if (st.images.length == _imageUrls.length) {
SearchTileModel newModel = st;
newModel.images = _imageUrls;
await _collec
.doc('${newModel.placeName} : name')
.set(
st.toJson(),
SetOptions(mergeFields: [
'images',
]),
)
.whenComplete(() {
return completed = true;
}).catchError((onError) {
print('${onError.toString()}');
completed = false;
});
}
} else {
completed = false;
print('Error from image repo ${snapshot.error.toString()}');
throw ('This file is not an image');
}
})
: print('No Images Selected');
if (data.length == 0) {
SearchTileModel newModel = st;
newModel.images = _imageUrls;
await _collec
.doc('${newModel.placeName} : name')
.set(
st.toJson(),
SetOptions(mergeFields: [
'images',
]),
)
.whenComplete(() {
return completed = true;
}).catchError((onError) {
print('${onError.toString()}');
completed = false;
});
}
return completed;
}
Here's Debug Console Output
All the print Statements showing the method is not running.
I also thought that due to await it was taking time but no after waiting for 10 mins nothing happened.
I/flutter (14005): true
I/flutter (14005): redtfgn
I/flutter (14005): File:
'/storage/emulated/0/Android/data/com.example.medium/files/Pictures/scaled_ec614e8a-0522-4cae-97be-
3ed50356de9c3343447263121135351.jpg'
I/flutter (14005): 1
I/flutter (14005): running
I/flutter (14005): 0
I/flutter (14005): File:
'/storage/emulated/0/Android/data/com.example.medium/files/Pictures/scaled_ec614e8a-0522-4cae-97be-
3ed50356de9c3343447263121135351.jpg'
I/flutter (14005): Till Here the code is Running
Update Got these lines
I/BiChannelGoogleApi(17801): [FirebaseAuth: ] getGoogleApiForMethod()
returned Gms: com.google.firebase.auth.api.internal.zzaq#cdf79f2
E/StorageUtil(17801): error getting token
java.util.concurrent.TimeoutException: Timed out waiting for Task
D/NetworkSecurityConfig(17801): No Network Security Config specified, using
platform default
W/NetworkRequest(17801): no auth token for request
I changed the rule of firebase storage too
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write ;
}
}
}
I can see that you are using .ref() in order to get the reference.
Checking the documentation, you can see that the used one is getReference()
StorageReference storageRef = storage.getReference();
Therefore, it might be better to set the storage reference as indicated in the documentation. Also the code for uploading the file would be like this:
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);