New Flutter Cloud Firestore [duplicate] - firebase

This question already has answers here:
No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase
(27 answers)
Closed 2 years ago.
I started to learn flutter again (started some time ago but stopped). You may find my code below. If I run the app on my smartphone it gives me the error: [core/no-app] No Firebase App['DEFAULT'} has been created - call Firebase.initializeApp(). I read in the documentation, but since I use the recent versions firebase_core: ^0.5.0, firebase_auth: ^0.18.0+1, cloud_firestore: ^0.14.0+2
it seems like the documentation isnt finished or I didnt get it. Where do I need to initialize that one? Why isnt that one enough: CollectionReference users = FirebaseFirestore.instance.collection('users');
timeline.dart (code is mostly from flutter getting started):
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:example/widgets/header.dart';
import 'package:example/widgets/progress.dart';
class Timeline extends StatefulWidget {
#override
_TimelineState createState() => _TimelineState();
}
class _TimelineState extends State<Timeline> {
#override
void initState() {
// getUserById();
super.initState();
}
#override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
return StreamBuilder<QuerySnapshot>(
stream: users.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return new ListView(
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document.data()['username']),
subtitle: new Text(document.data()['posts_count']),
);
}).toList(),
);
},
);
}
}
This is my code for main.dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'pages/home.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Example',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.red,
accentColor: Colors.blue,
),
home: Home(),
);
}
}
Thank you so much in advance!

In your main.dart, add the following
void main() async {
WidgetsFlutterBinding.ensureInitialized(); //add this
await Firebase.initializeApp(); //initialize here
runApp(MyApp());
}
Visit the new docs to learn more about working with the firebase packages

You can modify your MyApp widget like this, to make things work.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
print(snapshot.error.toString());
return Center(child: Text('Error'));
} else {
// ! RETURN THE SCREEN YOU WANT HERE
return Timeline();
}
},
),
);
}
}

Related

Error "[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()" is thrown [duplicate]

This question already has answers here:
No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase
(27 answers)
Closed 1 year ago.
I have a main file which returns home page and on the home page I am trying to call a new file (test.dart). Now the problem is this test.dart file is throwing some errors which I am unable to solve as I am completely new to flutter and Firebase Firestore.
Here is the code for test.dart:
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
// import 'package:vola1/colors.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
class test extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
// floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('countries')
.doc('nW9L4LGpn2MZVyiTyUII')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading data.. please wait..');
return Container();
},
));
}
}
This is the error it is throwing
======== Exception caught by widgets library =======================================================
The following FirebaseException was thrown building test(dirty):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
test file:///D:/flutter%20course/vola1/lib/home.dart:88:49
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:122:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:54:41)
#2 FirebaseFirestore.instance (package:cloud_firestore/src/firestore.dart:40:21)
#3 test.build (package:vola1/test.dart:15:33)
#4 StatelessElement.build (package:flutter/src/widgets/framework.dart:4569:28)
...
====================================================================================================
main file
import 'package:flutter/material.dart';
import 'home.dart';
void main() async {
runApp(MyApp());
await Firebase.initializeApp();
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
home page where the button is calling test.dart
ElevatedButton(
onPressed: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => test(),
),
),
},
Before using Firebase, you have to call Firebase.initializeApp(); You could do it like this:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

[Flutter]"[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()" even though app initialized

My main.dart:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:ruum/screens/login_screen.dart';
import 'package:ruum/screens/ruum_screen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
/* #override
void initState() {
// TODO: implement initState
super.initState();
Firebase.initializeApp().whenComplete(() => null);
} */
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, appSnapshot) => MaterialApp(
title: 'ruum',
theme: ThemeData(
primarySwatch: Colors.red,
backgroundColor: Colors.blueGrey,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, userSnapshot) {
if (userSnapshot.hasData) {
return RuumScreen();
}
return LoginScreen();
},
),
routes: {
RuumScreen.routeName: (ctx) => RuumScreen(),
},
),
);
}
}
I am using the FutureBuilder because I will be using the Future later in the code. I am getting this error anyway.
[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
[38;5;244mThe following FirebaseException was thrown building FutureBuilder<FirebaseApp>(dirty, state: _FutureBuilderState<FirebaseApp>#19dc7):[39;49m
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
[38;5;244mThe relevant error-causing widget was[39;49m
[38;5;248mFutureBuilder<FirebaseApp>[39;49m
[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;244m#0 MethodChannelFirebase.app[39;49m
[38;5;244m#1 Firebase.app[39;49m
[38;5;244m#2 FirebaseAuth.instance[39;49m
[38;5;248m#3 _MyAppState.build.<anonymous closure>[39;49m
[38;5;244m#4 _FutureBuilderState.build[39;49m
[38;5;244m...[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m
what might be causing this? I have added every thing to the gradle files and added the config file to the android directory.
edit: The LoginScreen does load after Future resolves.
I solved it by adding a tertiary operator before the StreamBuilder with a SplashScreen. I used the connection state property of the Future.
return FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, appSnapshot) => MaterialApp(
title: 'ruum',
theme: ThemeData(
primarySwatch: Colors.red,
backgroundColor: Colors.blueGrey,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: appSnapshot.connectionState == ConnectionState.waiting
? SplashScreen()
: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, userSnapshot) {
if (userSnapshot.hasData) {
return RuumScreen();
}
return LoginScreen();
},
),

How do I revert back to cloud firestore after running firebase emulator suite

I successfully installed and ran the firestore emulator but I now want to revert back to cloud firestore.
I thought if I would just remove FirebaseFirestore.instance.settings then it would revert to default. I have tried FirebaseFirestore.instance.settings =Settings() to set it back to default but its not working. Please help.
My code before running emulator
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
// import 'package:cloud_firestore/cloud_firestore.dart';
// import 'package:flutter/foundation.dart';
import './routes_theme.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(Tapp());
}
class Tapp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
// Set the host as soon as possible.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {
print('error');
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
// Otherwise, show something whilst waiting for initialization to complete
return RoutesAndTheme();
},
);
}
}
my code after I ran emulator:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import './routes_theme.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(Tapp());
}
class Tapp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
final String host = defaultTargetPlatform == TargetPlatform.android
? '10.0.2.2:8080'
: 'localhost:8080';
// Set the host as soon as possible.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {
print('error');
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
FirebaseFirestore.instance.settings =
Settings(host: host, sslEnabled: false);
// Otherwise, show something whilst waiting for initialization to complete
return RoutesAndTheme();
},
);
}
}

Flutter video_player with URL from Firestore Document

I'm trying to play a video from a URL of a Firestore Document. To play a video in Flutter, I have to instantiate its Url in the init() method. I set a default URL to a butterfly video, and the value was supposed to be replaced by the URL obtained from Firestore. (So that it is easy for me to see if the code works). However, the code does not work properly. I got an error that says "NoSuchMethodError: The getter 'value' was called on null".
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// Create the initialization Future outside of build
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
// Check for error
if (snapshot.hasError) {
print(snapshot.error);
return Center(
child: Container(
child: Text(
"Something went wrong",
textDirection: TextDirection.ltr,
),
),
);
}
//Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return MaterialApp(
title: 'Flutter Demo',
home: VideoPlayerScreen(),
);
}
return CircularProgressIndicator();
});
}
}
class VideoPlayerScreen extends StatefulWidget {
#override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
FirebaseFirestore firestore = FirebaseFirestore.instance;
String videoUrl =
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4';
#override
void initState() {
firestore.collection("videos").get().then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
// _controller.dispose();
videoUrl = doc["videoUrl"];
_controller = VideoPlayerController.network(videoUrl);
_initializeVideoPlayerFuture = _controller.initialize();
print(videoUrl);
})
});
// _controller = VideoPlayerController.network(videoUrl);
// _initializeVideoPlayerFuture = _controller.initialize();
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Video Player"),
),
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
children: [
AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
),
],
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
if (_controller.value.isPlaying) {
_controller.pause();
} else {
_controller.play();
}
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
Try the following:
#override
void initState() {
super.initState();
firestore.collection("videos").get().then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
videoUrl = doc["videoUrl"];
_controller = VideoPlayerController.network(videoUrl);
_initializeVideoPlayerFuture = _controller.initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});
});
});
}
Since initialize() is asynchronous, then you can use the method then which will get called when the future completes. Inside the callback, you can call setState() which will trigger a rebuild and notify the framework that the internal state of the widgets has changed .
https://pub.dev/packages/video_player

Firebase analytics only works sporadically

I have added Firebase analytics to a Flutter app, but when I try it with the debug view in Firebase, only some of the events are logged. And when a screen_view event is logged, I don't get all the information (Like firebase_screen). Even when I try to log an event with analytics.logEvent(name: 'test') it usually doesn't work.
Initially I thought the problem was that I'm using onGenerateRoute, but I have tried to use routes as well without luck.
Here is my main.dart:
import 'package:brf/route_generator.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
static FirebaseAnalytics analytics = FirebaseAnalytics();
static FirebaseAnalyticsObserver observer = FirebaseAnalyticsObserver(analytics: analytics);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Title',
initialRoute: '/',
onGenerateRoute: RouteGenerator.generateRoute,
navigatorObservers: [observer],
);
}
}
And Here is RouteGenerator:
import 'package:flutter/material.dart';
import 'package:brf/screens/home.dart';
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
//Argument som skickas till ny sida
//final args = settings.arguments;
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => Home());
break;
case '/second':
return MaterialPageRoute(builder: (_) => Second());
default:
return MaterialPageRoute(builder: (_) => _ErrorRoute());
}
}
}
And finally the screens:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder(
stream: Firestore.instance.collection('test').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData)
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(onPressed: () {
Navigator.of(context).pushNamed('/second');
}),
Text(snapshot.data.documents[0]['test']),
],
);
else
return CircularProgressIndicator();
},
),
),
);
}
}
class Second extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
);
}
}

Resources