How Firebase Works Internally on Flutter Dependencies - firebase

Currently, I use Firebase in the Flutter project. Firebase Analytics library in detail.
However, I became curious when I used this library.
Firebase Analytics's services operate automatically without any method calls from the entry point.
All I have to do is add the dependencies of the project as follows:
dependencies:
firebase_analytics: ^8.3.1
I don't know what procedures this is internally activated and moved by.
Can any experts explain how this is possible internally?

Firebase Analytics's services operate automatically without any method
calls from the entry point.
All I have to do is add the dependencies of the project:
dependencies:
firebase_analytics: ^8.3.1
That is not correct as there are a couple more processes to set it up.
Here is the step from the package's documentation:
To use this plugin, add firebase_analytics as a dependency in your pubspec.yaml file.
You must also configure firebase analytics for each platform project: Android and iOS.
You need to add the FirebaseAnalytics object and the FirebaseAnalyticsObserver object to the MaterialApp:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static FirebaseAnalytics analytics = FirebaseAnalytics();
static FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Analytics Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
navigatorObservers: <NavigatorObserver>[observer],
home: MyHomePage(
title: 'Firebase Analytics Demo',
analytics: analytics,
observer: observer,
),
);
}
}
The FirebaseAnalyticsObserver creates a NavigatorObserver that sends events to FirebaseAnalytics.

Related

Flutter update widgets using firebase remote config

I am working on a flutter app and I want to update the widgets of a page without pushing new updates on the play store. I have researched a bit on this topic and found that I can use firebase remote config. My idea is to use firebase remote config to fetch the widgets and show them on the app so that I don't need to publish frequent updates for small changes.
For Example, the below code is used to show a circular loading bar:
import 'package:flutter/material.dart';
class LoadingWidget extends StatelessWidget {
const LoadingWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
child: const CircularProgressIndicator(
color: Colors.black,
),
);
}
}
But now even for the smallest change, let it be changes in color, alignment, or size I need to push a new update to the play store and users need to install the new update in order to reflect the changes.
I want to store the flutter widget in firebase remote config (JSON format) then in the app, it will fetch the JSON data from remote config and show the new changes.
Once your RemoteConfig, you need do add key-value pair to match your needs:
key : value
color : black
Thenm fetch the value:
myRemoteColor = remoteConfig.getString('color')
Now, your myRemoteColor has a string with value black.
Since you already know that Remote Config only stores primitive values, the problem becomes how to encode and decode a Flutter widget into a string.
I doubt that is going to be simple though, as it'd mean that your application would need to compile the JSON/string into a binary. You'd essentially be implementing something akin to Flutter's Hot Reload for your remote clients, something that'd be pretty cool but is not a built-in feature.
More feasible is to control specific widgets that you already have in your code, as for example Rubens answered. In a recent sample app I used Remote Config to enable/disable a new feature (a process known as feature flagging) with:
class _MyHomePageState extends State<MyHomePage> {
final FirebaseRemoteConfig remoteConfig;
_MyHomePageState(this.remoteConfig);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: remoteConfig.getBool("chat_enabled") ? 3 : 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
const Tab(icon: Icon(Icons.games_outlined)),
const Tab(icon: Icon(Icons.swap_vert_circle_outlined)),
if (remoteConfig.getBool("chat_enabled")) const Tab(icon: Icon(Icons.chat_bubble_outlined)),
],
),
title: Text(widget.title),
),
body: TabBarView(
children: [
const MyGame(key: Key('game')),
const Leaderboard(key: Key('leaderboard')),
if (remoteConfig.getBool("chat_enabled")) const Messageboard(key: Key('messageboard')),
],
),
),
),
);
}

flutter firebase MissingPluginException

I just added firebase to my flutter App, i followed all the steps correctly, but i'm getting an error when initializing the app
this is my code to initialize app
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: new ThemeData(
canvasColor: Colors.white,
),
home: PersistentTabsDemo(),
onGenerateRoute: route.controller,
);
}
}
this are the dependecies i added to pubsec.yaml
firebase_core: ^1.6.0
firebase_analytics: ^8.3.1
firebase_auth: ^3.1.0
cloud_firestore: ^2.5.1
and this is the error
Error: MissingPluginException(No implementation found for method Firebase#initializeCore on channel
plugins.flutter.io/firebase_core)
Edit: i tried removing async and await from my main class now i'm getting new error
No firebase App 'default' has been created - call Firebase.intializeApp()
Try
Flutter clean
Pub.get
If these two doesn't work
Something is missing in setup of Firebase flutter
If anyone else had the same issue as me
I've fixed the issue by creating another project and added the sh1 and sh256 to firebase
just follow this tuto it's really helpful https://www.youtube.com/watch?v=CpyALC8Zpxo
PS: when u add firebase to your flutter project don't run it on chrome debug you will get an error, run it on your emulator or smartphone
happy coding ^^

Flutter app error message: No Firebase App

I recently went back to a Flutter project I've not touched for a couple of months and updated a few bits and pieces. Now, when I run the app in my emulator, I get the message:
[core/no-app] No Firebase App '[DEFAULT]' has been created
I added this line of code to initialize it in the app: await Firebase.initializeApp();... but it now doesn't appear to connect to my Firebase, just an empty one that I presume it has created on the fly.
This was my original code, which according to this site is the correct way to initialize the app: https://firebase.flutter.dev/docs/overview/
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: FutureBuilder(
future: _initialization,
builder: (context, snapshot) {...
Any idea what I'm doing wrong? The original app on my phone works fine with Firebase, so I presume it's something to do with updating Flutter, Firebase to the latest versions.
Thanks
You should initalize your app in the main function before you run your app, not in the MyApp widget.
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); // add this line
runApp(MyApp());
}
Ah, it wasn't anything to do with the incorrect Firebase app. I did initialize it in the main function, but in debugging I found that it was hitting an error in reading an object from the database. It was just incorrectly defined. I fixed that and it works now.
Thanks

How to use Windows Authentication (Azure AD) in Flutter with Firebase

I am currently developing an app which requires windows authentication.
Access should only been given to users known in the azure active directory of the company.
I already:
created an app registration with read access to azure.
activated windows auth in my firebase project
There is some example code available on:
https://firebase.google.com/docs/auth/android/microsoft-oauth?authuser=0
but it is not very well explained where I can get some of the used classes like 'OnSuccessListener' etc.
I would appreciate if someone can provide me some best practice code how to use the windows auth in flutter with firebase or also without firebase. Hopefully there is a possibility without storing the app registration secretly in the code.
In the end I need the usertoken to make api calls.
Without Firebase you have the msal_mobile [1] package that will Authenticate with Azure AD on iOS and Android.
There's step-by-step instructions within the package for setting up within the Azure portal, along with the iOS and Android platforms. Then the Flutter code to sign-in is simply:
await msal.signIn(null, ["api://[app-registration-client-id]/user_impersonation"]).then((result) {
print('access token: ${result.accessToken}');
})
Link
[1]: https://pub.dev/packages/msal_mobile
There is now a way for you to sign in with Microsoft using Firebase Auth but at the time of writing, I haven't seen a way to use it in tandem with MS Graph. For those who don't need graph access, here's the method I used:
Pubspec.yaml
firebase_auth: ^0.18.3
firebase_core: ^0.5.2
Your Widget
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: RaisedButton(
child: Text('login'),
onPressed: () async {
try {
User user =
await FirebaseAuthOAuth().openSignInFlow("microsoft.com", [
"https://graph.microsoft.com/User.Read",
"https://graph.microsoft.com/User.ReadBasic.All"
], {
'tenant': '' //Your tenant ID here
});
print(user);
} on PlatformException catch (error) {
debugPrint("${error.code}: ${error.message}");
}
},
),
),
);
}
}
Assuming you've setup Firebase Auth and Azure App registrations properly, this should be enough for you to sign in via MS

How to log Firebase Analytics events in Flutter

I want to log Firebase event in Flutter, but I cannot log any event.
I want to count what times events are done, so when tapping the button, I log the event.
class Onboarding extends StatefulWidget {
Onboarding({Key key, this.analytics, this.observer})
: super(key: key);
final FirebaseAnalytics analytics;
final FirebaseAnalyticsObserver observer;
#override
_OnboardingState createState() => _OnboardingState(analytics, observer);
}
class _OnboardingState extends State<Onboarding> {
_OnboardingState(this.analytics, this.observer);
final FirebaseAnalyticsObserver observer;
final FirebaseAnalytics analytics;
...
Future<void> _sendAnalyticsEvent(FirebaseAnalytics analytics,
FirebaseAnalyticsObserver observer) async {
await analytics.logEvent(
name: 'onboarding'
);
}
Materialbotton(
child: onPressed: () async {
_sendAnalyticsEvent(analytics, observer);
...
}
)
However, if I see Firebase console, I see nothing
Per my understanding, it takes 24 hours in general to see the events logged in firebase console. But to see if the events are indeed being logged, you can use debugView, located under Analytics sidebar in firebase console.
Before you could use debugView, you'll need to configure the setting by enabling respective emulator or simulator on which you're running the app, as explained here
Once you enable it, you should be able to see the events being logged as you perform action in the app.
Hope this helps.

Resources