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

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?

Related

Force cache refresh on flutter v3.0.1 web

In the current version of flutter 3.0.1 we have a service worker in index.html. So far, I cannot find any documentation on flutter.dev for how to force a cache refresh when screens or code has updated. The only way to refresh is using browser refresh buttons, etc.
There is a lot of outdated suggestions on SO to change the version number manually by appending something here or there, but that does not apply to the serviceworker. The service worker when running flutter build web automatically gets a new version number each time you build. This does not, however, force a cache refresh in the browser.
By default this service worker js is listening for a statechange and then calling console.log('Installed new service worker.'); This is only called when you click the browser's refresh button, so it is not helpful to prompt or force a refresh for new content.
I tried using flutter build web --pwa-strategy=none and this does not affect caching either.
Any bright ideas out there to force a refresh? In other websites I've built it was very easy to version css/js files, which would force a refresh without any user interaction, but I'm not seeing any clear paths with flutter build web.
This is the serviceWorker js in web/index.html.
After running flutter build web the var serviceWorkerVersion = null will become something like var serviceWorkerVersion = '1767749895'; when deployed to hosting and live on the web. However, this serviceWorkerVersion update does not force a refresh of content.
<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>
Have you tried this? Adding the no-cache in the index.html. Seems like working on Flutter 3.0. Keep in mind that by doing this your pwa will not work in offline mode.
<head>
...
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="pragma" content="no-cache" />
...
</head>

Cordova Facebook login

I installed the plugin as mentioned in the docs
I cant find a way to get it working.
When I run the apk on android I get this:
Uncaught ReferenceError: facebookConnectPlugin is not defined(…)
Here are me files.
index.html
<body>
<div class="app">
<div id="fb-root"></div>
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
<div id="fb-root"></div>
index.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
//FB login
facebookConnectPlugin.login(
["public_profile"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
}
}
};
app.initialize();
I've had issues with using the FB plugin in my app development too. Sometimes it's necessary to include the FacebookConnectPlugin.js file in your index.html, as well as include this script, which injects the Facebook Javascript SDK into your app.
Source: https://github.com/driftyco/ng-cordova/issues/446
Other threads about the same issue:
Cordova/Phonegap-facebook-plugin Android: facebookConnectPlugin is not defined
facebookConnectPlugin is not defined
facebookConnectPlugin is not defined (ngCordova, Ionic app)
...

How to implement OAuth.io using Ionic Framework for LinkedIn?

I have created the LinkedIn app and retrieved the client id and client_secret.
Now inside the integrated api of OAuth.io created an api and have added the keys and permission scope.
I want to run this project using Ionic Framework. What should be done to achieve it.
P.S: I am new to Ionic Framework and OAuth.io. So please don't mind my style of asking the question.
whole index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="js/ng-cordova-oauth.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button class="button" ng-click="linkedInLogin()">Login via LinkedIn</button>
</body>
</html>
whole app.js:
angular.module('starter', ['ionic', 'ngCordova', 'ngCordovaOauth'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller("MainCtrl", function($scope, $cordovaOauth) {
document.addEventListener( "deviceready", onDeviceReady );
function onDeviceReady( event ) {
// on button click code
$scope.linkedInLogin = function(){
OAuth.initialize('07IxSBnzVoGGQL2MpvXjSYakagE')
OAuth.popup('linkedin').done(function(result) {
// Here you will get access token
console.log(result)
result.me().done(function(data) {
// Here you will get basic profile details of user
console.log(data);
})
});
};
}
});
Please go through the steps and below code:
1) create a project from terminal as ionic start linkedinlogin blank
2)cd linkedinlogin project
3)Add the required platform in terminal as ionic add platform ****
4)Add the ng-cordova.min.js file above the cordova.ja file in our project
5)Install ng-cordova-oauth as bower install ng-cordova-oauth -S
6)Then include ng-cordova-oauth.min.js file in index.html
7)Inject 'ngCordova' and 'ngCordovaOauth' as dependency in app.js file
8)In index.html create a button as login via linkedin
9)In app.js create a Controller with below code
10)Please update your cordova platform if the above plugin doesn't work
$cordovaOauth.linkedin(clientId, clientSecret, ['r_basicprofile', 'r_emailaddress']).then(function(success){
//Here you will get the access_token
console.log(JSON.stringify(success));
$http({method:"GET", url:"https://api.linkedin.com/v1/people/~:(email-address,first-name,last-name,picture-url)?format=json&oauth2_access_token="+success.access_token}).success(function(response){
// In response we will get firstname, lastname, emailaddress and picture url
// Note: If image is not uploaded in linkedIn account, we can't get image url
console.log(response);
}, function(error){
console.log(error);
})
}, function(error){
console.log(error);
})
I thing you read the ngCordova plugins.
Using oauth.io i have implemented login via linkedin:
Please follow the steps:
1. Create a app in oauth.io and get public key.
2. Click on the Integrated APIs menu from the left side bar.
3. Now click on ADD APIs green button on the right top corner.
4. Now Search and select LinkedIn.
5. Now add the Client id and Client Secret in keys and permission scope.
6. use below command to add plugin to project:
cordova plugin add https://github.com/oauth-io/oauth-phonegap
7. For controller code check below code.
document.addEventListener( "deviceready", onDeviceReady );
function onDeviceReady( event ) {
// on button click code
$scope.linkedInLogin = function(){
OAuth.initialize('your public key')
OAuth.popup('linkedin').done(function(result) {
// Here you will get access token
console.log(result)
result.me().done(function(data) {
// Here you will get basic profile details of user
console.log(data);
})
});
};
}
Hope it may be help you..

Azure Media Player Uncaught Error: cannot find the request in the request queue

I have a problem I do not know how to solve, I do not know if it's a bug of 'azure media player' but when I view a streaming video shows me this error "'Uncaught Error: cannot find the request in the request queue azuremediaplayer.min.js (2,338210)' but if I see a local video as a mp4 does not give me any problems. What could be the problem? Excuse my English.
By the way, I'm using Ripple to emulate Android, if I visualize from a physical device does not give me problems.
Thanks
(function () {
"use strict";
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
var myOptions = {
"nativeControlsForTouch": false,
controls: false,
autoplay: false,
width: "640px",
height: "360px",
poster: "",
logo: {
enabled: false
}
}
var myPlayer = amp("azuremediaplayer", myOptions);
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
//var element = document.getElementById("deviceready");
//element.innerHTML = 'Device Ready';
//element.className += ' ready';
myPlayer.src([
{
//"src": "movie/Rutina.mp4",
//"type": "video/mp4"
"src": "http://amssamples.streaming.mediaservices.windows.net/830584f8-f0c8-4e41-968b-6538b9380aa5/TearsOfSteelTeaser.ism/manifest",
"type": "application/vnd.ms-sstr+xml",
"protectionInfo": [
{
"type": "AES",
"authenticationToken": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cm46bWljcm9zb2Z0OmF6dXJlOm1lZGlhc2VydmljZXM6Y29udGVudGtleWlkZW50aWZpZXIiOiI5ZGRhMGJjYy01NmZiLTQxNDMtOWQzMi0zYWI5Y2M2ZWE4MGIiLCJpc3MiOiJodHRwOi8vdGVzdGFjcy5jb20vIiwiYXVkIjoidXJuOnRlc3QiLCJleHAiOjE3MTA4MDczODl9.lJXm5hmkp5ArRIAHqVJGefW2bcTzd91iZphoKDwa6w8"
}
]
}
]);
myPlayer.autoplay(true);
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )();
<!DOCTYPE html>
<html>
<head>
<!--
Customize the content security policy in the meta tag below as needed. Add 'unsafe-inline' to default-src to enable inline JavaScript.
For details, see http://go.microsoft.com/fwlink/?LinkID=617521
-->
<meta http-equiv="Content-Security-Policy" content="default-src http://amp.azure.net 'self' data: gap: blob: https://ssl.gstatic.com http://amssamples.streaming.mediaservices.windows.net 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self'; media-src http://localhost:4400/ blob:">
<title>Mobile</title>
<link href="lib/ionic/release/css/ionic.css" rel="stylesheet" />
<link href="http://amp.azure.net/libs/amp/1.6.3/skins/amp-default/azuremediaplayer.min.css" rel="stylesheet" />
<script src="http://amp.azure.net/libs/amp/1.6.3/azuremediaplayer.min.js"></script>
</head>
<body>
<video id="azuremediaplayer" class="azuremediaplayer amp-default-skin amp-big-play-centered"></video>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"></script>
<script src="lib/ionic/release/js/ionic.bundle.js"></script>
<script src="scripts/index.js"></script>
</body>
</html>
Unfortunately, using an emulator for video playback can be an unreliable testing scenario. The issue you're seeing could very well be unique to the emulator itself, which can be dependent on the performance of the machine your emulator is running on as well as the capabilities of the emulator.
You are better of testing your code on a physical device, especially if the issue is not occurring on it.

Looking for working example of WP7 PhoneGap Facebook plugin for signin button

I've tried all the code at https://github.com/davejohnson/phonegap-plugin-facebook-connect
that is recommended by the phonegap community, but i keep running into errors trying to get it to work.
As you can see I'm using cordova 1.6.0 which maybe the problem?
i've added the script files to in my html page
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>
<script type="text/javascript" charset="utf-8" src="cdv-plugin-fb-connect.js">/script>
<script type="text/javascript" charset="utf-8" src="facebook_js_sdk.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
And I've added the ChildBrowserCommand.cs into the plugins directory.
I then added this to device ready listener with my authentic app id (the real id not shown here)
document.addEventListener("deviceready",onDeviceReady,false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
//document.getElementById("welcomeMsg").innerHTML += "Cordova is ready! version=" + window.device.cordova;
console.log("onDeviceReady. You should see this message in Visual Studio's output window.");
//fb connect sign in
try {
//alert('Device is ready! Make sure you set your app_id below this alert.');
console.log('Device is ready! Make sure you set your app_id below this alert.');
FB.Cookie.setEnabled(true); // this seems to be duplicate to 'cookie: true' below, but it is IMPORTANT due to FB implementation logic.
FB.init({ appId: "311961255484993", nativeInterface: CDV.FB, cookie: true });
login();
} catch (e) {
//alert(e);
console.log("Init error: " + e);
}
};
function login() {
FB.login(
function (response) {
if (response.session) {
console.log('logged in');
} else {
console.log('not logged in');
}
},
{ scope: 'email, read_stream, read_friendlists' }
);
}
The error i get is
Unable to locate command :: org.apache.cordova.facebook.Connect
Any help?
EDIT: I also realize it's coming from cdv-plugin-fb-connect.js in here but not sure why?
cordova.exec(function () {
var authResponse = JSON.parse(localStorage.getItem('cdv_fb_session') || '{"expiresIn":0}');
if (authResponse && authResponse.expirationTime) {
var nowTime = (new Date()).getTime();
if (authResponse.expirationTime > nowTime) {
// Update expires in information
updatedExpiresIn = Math.floor((authResponse.expirationTime - nowTime) / 1000);
authResponse.expiresIn = updatedExpiresIn;
localStorage.setItem('cdv_fb_session', JSON.stringify(authResponse));
FB.Auth.setAuthResponse(authResponse, 'connected');
}
}
console.log('Cordova Facebook Connect plugin initialized successfully.');
}, (fail ? fail : null), 'org.apache.cordova.facebook.Connect', 'init', [apiKey]);
},