Flutter crashes when importing 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)
"The operator '[]' isn't defined" error when using .data[] in flutter firestore
(6 answers)
The getter 'instance' isn't defined for the type 'Firestore'
(2 answers)
Closed 2 years ago.
I'm trying to fetch data from Cloud Firestore on flutter but as soon as I import the cloud_firestore.dart package, the app doesn't even build and crashes instantly with a lot of errors.
https://hastebin.com/esuzizuzod.sql this is the error it throws.
And this is the code
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Firestore Demo"),
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection("users").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text("Loading data...Please wait!");
} else {
return Column(
children: <Widget>[
Text(snapshot.data.documents[0]["name"]),
Text(snapshot.data.documents[0]["age"]),
Text(snapshot.data.documents[0]["role"]),
],
);
}
}),
);
}
}
I have also implemented all the packages in the pubspec.yaml file.
Does anyone know how to fix this?
Thanks

Related

Where to add Firebase.initializeApp in flutter? [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.
Error : no firebase app has been created call firebase.initializeapp
My Question : Where should i need to add firebase initialization
A stateless widget with firestore reference 'users'
class FeedBack extends StatelessWidget {
CollectionReference users = FirebaseFirestore.instance.collection('users');
late String txtnote;
late String note;
#override
Widget build(BuildContext context) {
return Scaffold(
onpress integration for writing data to firestore
child: ElevatedButton(
onPressed: () async {
await users.add({
'subject': note,
'email': 'example#gmail.com',
'description': txtnote
}).then((value) => print('Data Added Successfully!'));
},
child: Text(
'Submit',
style: TextStyle(color: Colors.white),
),
Note : This dart file 'feedback.dart' does not contain void main function its a stateless widget
You can call inside the main entry point of your app:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
As a default, this should go in the main.dart file
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

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 - getting data from stream builder of other page [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to get firestore data from streambuilder of other page, and it shows me the below error
error: The method 'data' isn't defined for the type 'QuerySnapshot'.
(undefined_method at [phonebook_admin]lib\Screens\DetailPage\DetailPage.dart:20)
The below is the code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class DetailPage extends StatefulWidget {
final QuerySnapshot contactDetail;
DetailPage({this.contactDetail});
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Container(
child: Card(
child: ListTile(
title: Text(widget.contactDetail.data()['name']),
subtitle: Text(widget.contactDetail.data()['email']),
),
),
);
}
}
You should do the following:
return ListView.builder(
shrinkWrap: true,
itemCount: widget.contactDetail.docs.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(widget.contactDetail.docs[index].data()['name']),
subtitle: Text(widget.contactDetail.docs[index].data()['email']),
);
},
);
QuerySnapshot returns a list of documents with the content of the documents, therefore you need to use a ListView.builder

New Flutter Cloud Firestore [duplicate]

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();
}
},
),
);
}
}

Flutter : problem writing the document in firebase

I made a list of documents in firestore in firebase with image , title , price and number(index of doc) property when I write values in property in firestore they didint update all in application some of them are miss as NULL in consell run .
to fix it :
to fix the issue is to make update in value again so will fix but who will update it so many time.
The full code is :
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void main() => runApp(MaterialApp(
home: Home(),
));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
void initState() {
// TODO: implement initState
super.initState();
GetDatafromFirebase();
}
GetDatafromFirebase() {
Firestore.instance
.collection('DesginStore')
.document('Logo')
.collection('sub')
.orderBy('number',descending: false)
.snapshots()
.listen((data) =>
data.documents.forEach((doc) => print("Title is :${doc["title"]} And for order number is ${doc["number"]}")));
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text('Fortesting'),
],
);
}
}
the result in app is(video) :
https://drive.google.com/file/d/1FCKI3W5XTmVgTbtXKpYLHMrzAFya7AgQ/view?usp=sharing
I would suggest familiarizing with some of the architectures used by other developers.
https://codewithandrea.com/videos/2020-02-10-starter-architecture-flutter-firebase/
or taking a look at this
Flutter - Get array from Firestore with FutureBuilder (using query)
Only difference would be that you need to call setState on listening to changed data.

Resources