flutter web not working due to await statement - flutter

I am having issues with Flutter web when I use await statement,
void main() async {
//debugPaintSizeEnabled = true;
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
this will not display anything on the browser and throws and error:
ChromeProxyService: Failed to evaluate expression 'title': InternalError: Expression evaluation in async frames is not supported. No frame with index 39..
I am stuck :(
debugging testing nothing worked

Run flutter channel stable followed by flutter upgrade --force

When using Firebase, you need to initalize it with options for the specific platform that you are using. Here goes and example on how to configure it for Flutter Web:
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
void main() async {
//debugPaintSizeEnabled = true;
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options = FirebaseOptions(
apiKey: 'YOUR API KEY',
appId: 'YOUR APP ID',
messagingSenderId: 'YOUR MESSAGING SENDER ID',
projectId: 'YOUR PROJECT NAME',
authDomain: 'YOUR AUTH DOMAIN (IF YOU HAVE)',
databaseURL: 'YOUR DATABASE URL (IF YOU USE FIREBASEDATABASE)',
storageBucket: 'YOUR STORAGE BUCKET',
)
);
runApp(MyApp());
}
All this information is available on your Firebase Project Console, just search for it. Hope it helps!

Related

FB.login() called before FB.init() - Flutter

Trying to:
Authorize via facebook login on web
Problem:
I get the error: FB.login() called before FB.init().
What I'm doing:
I'm using package flutter_facebook_auth: ^5.0.6 for my flutter project. It works fine with Android and iOS, but fails on web.
The main.dart-file initialises facebook before I call the login, so I'm not sure what I need to do. This is my main-file:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if(kIsWeb){
await FacebookAuth.i.webAndDesktopInitialize(
appId: "provided in the real code",
cookie: true,
xfbml: true,
version: "v14.0"
);
}
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const ProviderScope(child: App()));
}
.
.
.

How to share Flutter source code for projects linked to Firebase?

I have a Flutter project linked to my Firebase account (using FlutterFire CLI).
Now that I finished the project I want to sell the source code.
How can I change the Firebase account linked to this project?
When using FlutterFire CLI, it generates a file called firebase_options.dart containing Firebase options for each platform like this:
static const FirebaseOptions android = FirebaseOptions(
apiKey: '-------',
appId: '------',
messagingSenderId: '-----',
projectId: '----------',
storageBucket: '--------',
  );
Do I have just to change these values? If yes, where can I find all of them?
main.dart
import 'firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
Full firebase_options.dart file
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for ios - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: '------',
appId: '------',
messagingSenderId: '-----',
projectId: '------',
authDomain: '--------',
storageBucket: '--------',
measurementId: '--------',
);
static const FirebaseOptions android = FirebaseOptions(
apiKey: '----',
appId: '----',
messagingSenderId: '--------',
projectId: '------',
storageBucket: '--------',
);
}
I tried to change the values (in firebase_options.dart) and that caused this error:
E/flutter (26545): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
it throws this error(duplicateApp from method_channel_firebase.dart):
// If there is a native default app and the user provided options do a soft
// check to see if options are roughly identical (so we don't unnecessarily
// throw on minor differences such as platform specific keys missing
// e.g. hot reloads/restarts).
if (defaultApp != null && _options != null) {
if (_options.apiKey != defaultApp.options.apiKey ||
(_options.databaseURL != null &&
_options.databaseURL != defaultApp.options.databaseURL) ||
(_options.storageBucket != null &&
_options.storageBucket != defaultApp.options.storageBucket)) {
// Options are different; throw.
throw duplicateApp(defaultFirebaseAppName);
}
// Options are roughly the same; so we'll return the existing app.
}
You can change the firebase account linked to this project. This error that you are seeing
E/flutter (26545): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
is caused by the original gradle sync operation generating a Google-Services.json file and using it within the app. To remove this error, switch into the android folder from your main flutter project and run
./gradlew clean
This command calls the gradle wrapper which then cleans the project and brings it back to its original state. The flutter team uses a default empty flutter_options.dart file for their projects. You may want to consider doing that if you are seeing the source code to someone. I would just package instructions for how to configure their project to work with a new Firebase project that they would select.

Flutter Firebase Notification on Web

In my flutter project, I already have notifications set up using firebase_messaging for Android and iOS. I am trying to add the same for Web. I had tried it before (mostly changing index.html with firebase-configs and initializing), but it had not worked then and I had left it. Now their document asks to use the new way, which asks only to configure it in the dart-files, and talks nothing about doing anything on index or other js files. So I have removed imports, and initialization from index.html, and not added any other file ( I have tried adding empty firebase-messaging-sw.js and removing it). This is the error I am getting:
[firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:44055/firebase-cloud-messaging-push-scope') with script ('http://localhost:44055/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. .
What am I missing? Are those steps incomplete? I also tried the steps in this article , but still have the same issues.
Edit
These are all the code-parts related to firebase-messaging.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
firebaseAnalytics = FirebaseAnalytics.instance;
firebaseMessaging = FirebaseMessaging.instance; //
final notificationSettings = await firebaseMessaging.requestPermission();
debugPrint('User granted permission: ${notificationSettings.authorizationStatus}');
if (!kIsWeb) {
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'This channel is used for important notifications.',
// description
importance: Importance.max,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
.
.
.
.
.
.
.
.
if (kIsWeb) {
// this is where the code throws error:
token = (await firebaseMessaging.getToken(
vapidKey: "BLn....pH8",
))!;
} else {
token = (await firebaseMessaging.getToken())!;
}

Flutter Web + Firebase: [firebase_auth/argument-error]

I have a Flutter App that I'm simply building to web. I use pretty much the whole suite of Firebase tools. What happens is that whenever I try to call the any signIn method e.g. signInAnonymously or signInWithEmailAndPassword, I get an [firebase_auth/argument-error].
Regular firebase calls, like Firestore get() or update() are working fine.
This is my pubspec.yaml:
firebase_auth:
firebase_auth_web:
firebase_core:
firebase_core_web: ^1.7.3
firebase_storage:
firebase_analytics:
firebase_dynamic_links:
firebase_messaging:
cloud_firestore:
cloud_firestore_web:
cloud_functions:
I initialize Firebase like this in main.dart
if (Constants.BUILD_FOR_WEB) {
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: '',
authDomain: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
),
);
} else {
await Firebase.initializeApp();
}
Note: I removed all firebase configurations from index.html because I read that it isn't needed anymore. Since firestore calls worked after removing, I figured it was true.
What I am doing is simply calling my anonymousSignUp() function:
import 'package:firebase_auth_web/firebase_auth_web.dart' as authWeb;
import 'package:firebase_auth/firebase_auth.dart' as auth;
Future<void> anonymousSignUp() async {
try {
if (Constants.BUILD_FOR_WEB) {
await _authWeb.signInAnonymously();
} else {
await _auth.signInAnonymously();
}
} catch (e) {
print(e);
}
}
I get an [firebase_auth/argument-error], nothing more.
No console output, nothing in the network tab either.
I don't know what to do. If anybody has a clue, I'm incredibly thankful for everything.

Flutter web Firebase Firestore

I am trying to connect Firestore to my web project but it gives me "no firebase app has been created"
this is the way I used the script in the index file
<script src="https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.8/firebase-firestore.js"></script>
<script>
var firebaseConfig = {
apiKey: "-------cnto--------------",
authDomain: "---------.firebaseapp.com",
projectId: "---------",
storageBucket: "---------.appspot.com",
messagingSenderId: "---------48",
appId: "1:---------48:web:---------89"
};
firebase.initializeApp(firebaseConfig);
</script>
and this is the way I initialize the app
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
when I added await and async it waits forever and gives me a white screen like there is nothing to wait for
Setup the FlutterFire CLI and then run this in your terminal:
flutterfire configure
This tool is awesome and it makes it so you never have to touch native files again when setting up Firebase.