Flutter web: Firestore work in run debug mode and don't work in bilud release mode - flutter

**I am trying to update the data using firestore, it works fine on the phone and run web but it does not work when I do a build and upload file to my server --
index.html >> **
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-app.js";
import { getFirestore, collection, getDocs } from 'https://www.gstatic.com/firebasejs/9.9.3/firebase-firestore.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: -----,
authDomain: ------,
projectId: ------,
storageBucket: ------,
messagingSenderId: ------,
appId: ------,
measurementId: ------
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
</script>
update firestore code>>
FirebaseFirestore.instance
.collection('orderDetails')
.doc(id)
.update({
'status': status,
}).catchError((e) {
print(e);
});
and get this error in browser console
Refused to load the script 'https://www.gstatic.com/firebasejs/9.9.3/firebase-app.js' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' http://myserverurl.com https://myserverurl.com http://www.myserverurl.com https://www.myserverurl.com". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
also this error
VM86:3 Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: https://www.gstatic.com/firebasejs/9.9.0/firebase-app.js

Update your index.html in folder web to this :
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-analytics.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=yourKey"></script>
<script>
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: -----,
authDomain: ------,
projectId: ------,
storageBucket: ------,
messagingSenderId: ------,
appId: ------,
measurementId: ------
};
/// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
and on your server Edit your file .htaccess if you use set Header set Content-Security-Policy "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://example.com
remove it

Related

TypeError: Cannot read properties of undefined (reading 'init') || Flutter web

I have recently upgraded my flutter project from Flutter Beta to Flutter Stable 3.3.8.
after upgrading, I also upgraded all the firebase packages to the latest version.
Due to this upgrade on my config function, there is a new parameter of navigatorKey.
So I included that like this
class NavKey{
static final navKey = GlobalKey<NavigatorState>();
}
static final Config config = Config(
navigatorKey: NavKey.navKey, //new parameter of navigatorKey
tenant: "xx-3066-xx-xx-xx",
clientId: "xx-ad66-xx-a6e6-xx",
scope: "api://xx-xx-422a-a6e6-xx/xx",
redirectUri:
"xx://com.example.xx/xx%xx%3D");
Now If I run my project and enter my email id and hit enter it shows this error
TypeError: Cannot read properties of undefined (reading 'init')
on my void main() I have included all my Firebase initialize like this
Future<void> main() async {
// await dotenv.load();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "xxx-xx",
authDomain: "xx-xxx.firebaseapp.com",
databaseURL: "https://xxx-xx-default-xxx.xx.com",
projectId: "xxx-xxx",
storageBucket: "xxx-xx.appspot.com",
messagingSenderId: "xxx",
appId: "1:xx:web:xxx3d75b63xxxxe9",
measurementId: "G-xxxx")
);
runApp(const MyApp()
/* MaterialApp(//
home: MyApp())*/
);
}
on my index.html I have also included this script as I am running my project on flutter web
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-functions.js"></script>
These are my all errors
Well, I am not able to find the solution for the latest package.
That's why I rolled back my aad_oauth from ^0.4.0 to ^0.3.0 where it doesn't asked for navigatorKey
Config(
navigatorKey: NavKey.navKey,)

firebase storage: uploading jpg casuing Could not load the default credentials. on Node.js

const { initializeApp } = require("firebase-admin/app");
const { getStorage } = require("firebase-admin/storage");
const firebaseConfig = {
apiKey: "ajsoidjof",
authDomain: "asodijfo",
projectId: "sihfiasd",
storageBucket: "sadjofjosad",
messagingSenderId: "2039023423",
appId: "saoijdofijo3ijo2",
measurementId: "sijdofijeadsf",
};
initializeApp(firebaseConfig);
const bucket = getStorage().bucket();
bucket.upload("./1.jpg");
This causes Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information. error. And, how can I upload the 1.jpg to just the main storage folder?
You're using the Firebase Admin SDK for Node.js, but then trying to initialize it with the configuration data for a client-side SDK. That won't work, so you'll either have to initialize the Admin SDK as shown here or use the client-side Node.js SDK.

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.

Adding Flutter Web: How to Solve No Firebase App '[DEFAULT]' has been created

I have a fully functional App on Android and IOS, and now I want to have a web version taking advantage of Flutter's cross-platform features.
To do this, I created a "Chrome Device" from VS Code and I did the Firebase App registration within the Firebase console. In the index.html I included the configuration as explained in Flutter Firebase Installation Web ...
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="appname">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<title>AppName</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "xxx", //with my particular values
authDomain: "xxx",
databaseURL: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig); //
</script>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js';
scriptTag.type = 'application/javascript';
document.body.append(scriptTag);
}
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
navigator.serviceWorker.register(serviceWorkerUrl)
.then((reg) => {
function waitForActivation(serviceWorker) {
serviceWorker.addEventListener('statechange', () => {
if (serviceWorker.state == 'activated') {
console.log('Installed new service worker.');
loadMainDartJs();
}
});
}
if (!reg.active && (reg.installing || reg.waiting)) {
// No active web worker and we have installed or are installing
// one for the first time. Simply wait for it to activate.
waitForActivation(reg.installing || reg.waiting);
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
// When the app updates the serviceWorkerVersion changes, so we
// need to ask the service worker to update.
console.log('New service worker available.');
reg.update();
waitForActivation(reg.installing);
} else {
// Existing service worker is still good.
console.log('Loading app from service worker.');
loadMainDartJs();
}
});
// If service worker doesn't succeed in a reasonable amount of time,
// fallback to plaint <script> tag.
setTimeout(() => {
if (!scriptLoaded) {
console.warn(
'Failed to load app from service worker. Falling back to plain <script> tag.',
);
loadMainDartJs();
}
}, 4000);
});
} else {
// Service workers not supported. Just drop the <script> tag.
loadMainDartJs();
}
</script>
</body>
</html>
When I run the App in Chrome I get an Oh No! Error 5 in the browser and no error messages in the VS Code console.
If I include an await in the Firebase initialization line in index.html:
await firebase.initializeApp(firebaseConfig);
Again the Oh No! Error 5, but when I reload the page I get the following error on web_entrypoint.dart:
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created -
call Firebase App.initializeApp() (app/no-app).
at Object.u [as app] (https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js:1:18836) at
Object.getApp
(http://localhost:65003/packages/firebase_database_web/src/interop/app.dart.lib.js:630:89)
//... more debug lines
In my lib/src/pages/main.dart, which works fine on IOS and Android, I'm making sure to initialize the Firebase services first ...
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
final prefs = PreferenciasUsuario();
await prefs.initPrefs();
await PushNotificationsProvider.initializeApp();
FirebaseDatabase database;
database = FirebaseDatabase.instance;
database.setPersistenceEnabled(true);
database.setPersistenceCacheSizeBytes(10000000);
runApp(MyApp());
}
I've read most of the answers on the subject on StackOverflow, but they haven't worked for me, I don't know if it's because I'm doing it particularly with Flutter.
How can I resolve the No Firebase App '[DEFAULT]' error and get my application run on the web?

Flutter web Firebase analytics TypeError: dart.global.firebase.analytics is not a function

I am trying to use firebase analytics in flutter web and getting the following error:
TypeError: dart.global.firebase.analytics is not a function
at Object.analytics$ [as analytics] (http://localhost:5000/packages/firebase/src/top_level.dart.lib.js:110:102)
at new firebase_analytics_web.FirebaseAnalyticsWeb.new (http://localhost:5000/packages/firebase_analytics_web/firebase_analytics_web.dart.lib.js:56:64)
at Function.registerWith
index.html file script part is as following :
<body>
<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-auth.js"></script>
<script>
var firebaseConfig = {
apiKey: "*",
authDomain: "*",
databaseURL: "*",
projectId: "*",
storageBucket: "*",
messagingSenderId: "*",
appId: "*",
measurementId: "*"
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
pubspec :
firebase_analytics: ^5.0.16
flutter version is 1.20.0 beta
The problem was with my browser. I am using brave browser it was blocking google analytics script. that's why i was facing this error.
I think you have included only firebase_analytics in your pubspec.yaml.
Try adding Firebase Core plugin too, something like this
firebase_core: ^0.4.5
firebase_analytics: ^5.0.16
Further references:
https://firebase.flutter.dev/docs/analytics/overview
https://github.com/FirebaseExtended/flutterfire#firebase_core
Update these two packages to the most recent version
firebase_core
firebase_analytics