Undefined name 'firebase' Flutter - firebase

Hello I am trying to implement firebase authentication in my flutter app I am getting this error
Undefined name 'firebase'
Here is the code for reference:
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:multi_purpose_scope/Animation/FadeAnimation.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void>main() async{
WidgetsFlutterBinding.ensureInitialized();
}
class HomePage extends StatelessWidget {
final FirebaseApp _fbApp=Firebase.initializeApp();
final _formKey = GlobalKey<FormState>();
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
gotoSecondActivity(BuildContext context){
final mq=MediaQuery.of(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondActivity()),
);
}
#override
Widget build(BuildContext context) {
TextEditingController _emailControllerField=TextEditingController();
TextEditingController _passwordControllerField=TextEditingController();
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: RaisedButton(
onPressed: () async {
gotoSecondActivity(context);
try{
FirebaseUser user=(await FirebaseAuth.instance.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
));
if(user!=null){
Navigator.of(context).pushNamed(gotoSecondActivity(context).menu);
}
}
catch(e){
print(e);
_emailController.text='';
_passwordController.text='';
}
},
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/loginHeader.png'),
fit: BoxFit.fill
)
),
child: Stack(
children: <Widget>[
],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
FadeAnimation(1.8, Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(143, 148, 251, .2),
blurRadius: 20.0,
offset: Offset(0, 10)
)
]
),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(
color: Colors.grey[100]))
),
child: TextField(
controller: _emailControllerField,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
),
Container(
padding: EdgeInsets.all(8.0),
child: TextField(
obscureText: true,
controller: _passwordControllerField,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
)
],
),
)),
SizedBox(height: 30,),
FadeAnimation(2, Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
gradient: LinearGradient(
colors: [
Color.fromRGBO(214, 0, 27, 1),
Color.fromRGBO(214, 0, 27, 1),
]
)
),
child: Center(
child: Text("Login", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),),
),
)),
SizedBox(height: 70,),
FadeAnimation(1.5, Text("Forgot Password?",
style: TextStyle(
color: Color.fromRGBO(214, 0, 27, 1)),)),
],
),
)
],
),
),
)
),
);
}
}
class SecondActivity extends StatelessWidget {
gotoRegister(BuildContext context){
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>Register()),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Container(
height: 174,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/patient_list.png'),
)
),
child: Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
height: 128,
child: Text(
'Patient List',
style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 30,
color: Colors.white
),
),
)
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
gotoRegister(context);
},
tooltip: 'Increment',
child: Icon(Icons.add),
backgroundColor: Color.fromRGBO(214, 0, 27,1),
),
),
);
}
}
class Register extends StatelessWidget {
goBack(BuildContext context) {
Navigator.pop(context);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
children: <Widget>[
Stack(
alignment: Alignment.center,
children: <Widget>[
Image.asset('assets/images/patient_list.png'),
Text('Registration',style: TextStyle(fontWeight:FontWeight.bold,fontSize: 30,color: Colors.white),)
]
),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Name'),
const SizedBox(height:10),
const SampleTextField(hintText: 'Enter MR-Number'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Phone Number'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Hospital Name'),
const SizedBox(height:10),
FlatButton(
onPressed: () {
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
// materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
// visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(vertical: 20),
color: Color.fromRGBO(214, 0, 27,1),
child: const Center(
child: Text('Register User'),
),
),
]
),
),
),
),
);
}
}
class SampleTextField extends StatelessWidget {
const SampleTextField({
this.controller,
this.hintText = '',
});
final TextEditingController controller;
final String hintText;
#override
Widget build(BuildContext context) {
return TextField(
controller: controller,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(
width: 1,
color: Colors.black54,
),
),
hintText: hintText,
hintStyle: const TextStyle(
color: Colors.black54,
),
contentPadding: const EdgeInsets.only(left: 20),
),
// textAlign: TextAlign.center, // Align vertically and horizontally
);
}
}
class ForgotPassword extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
children: <Widget>[
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Your Email'),
FlatButton(
onPressed: () {
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
padding: const EdgeInsets.symmetric(vertical: 20),
),
]
),
),
),
),
);
}
}
I googled my problem but can't seem to find the solution to my problem. I do know that there is something wrong with my initialization but i cant seem to connect the dots and find out where am i going wrong

You have to have the firebase core package added
firebase_core: ^7.0.1 (check the actual package version)
flutter pub get
and add the package to your code
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(HomePage());
}

I fixed the issue by upgrading to a newer version of firebase_core (I went with 1.0.0)

You need to initialize your Firebase into your main method
First flutter pub get
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(HomePage());
}

Add 'firebase_core: ^1.7.0' to pubspec.yaml file. And then flutter pub get. problem will solved.

I had a similar problem. Using firebase_core : ^1.0.1 worked for me in Ubuntu.

As Shubham already mentioned you have to initialize the Firebase instance before using it - although it doesn't necessarily have to be put into main.
You can initialize it anywhere outside of the widget in which you are trying to use the Firebase instance.
Firebase lazily creates its instance (most likely via proxy pattern) because its creation is expensive.
Therefore it can't find it immediately after you are trying to reference it :)

Related

FormatException: Unexpected character (at character 1) error while using email_auth package

#Hello there! I am using email_auth: ^0.0.1+4 Package to confirm the user email also it worked fine for few days and I also registered 2 3 users but suddenly it has started showing this FormatException: Unexpected character (at character 1) and DOCTYPE html error. I have added signup file Please check and help. Thank you.#
SignUp Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vanfly/common.dart';
import 'package:vanfly/providers/user_provider.dart';
import 'package:vanfly/screens/home.dart';
import 'package:vanfly/widgets/loading.dart';
import 'package:email_auth/email_auth.dart';
bool verified = false;
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
TextEditingController _email = TextEditingController();
TextEditingController _password = TextEditingController();
TextEditingController _name = TextEditingController();
TextEditingController otp = TextEditingController();
bool hidePass = true;
void sendOTP() async {
EmailAuth.sessionName = 'Vanfly';
var res = await EmailAuth.sendOtp(receiverMail: _email.value.text);
if (res) {
_key.currentState.showSnackBar(SnackBar(
content: Text("An OTP has sent to your email please verify")));
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
}
}
bool verifyOTP(){
var res = EmailAuth.validate(receiverMail: _email.value.text, userOTP: otp.value.text);
if (res) {
return verified = true;
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
return verified = false;
}
}
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body: user.status == Status.Authenticating
? Loading()
: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey[350],
blurRadius:
20.0, // has the effect of softening the shadow
)
],
),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
alignment: Alignment.topCenter,
child: Image(
image: AssetImage(
'images/vanfly Logo/vanfly_logo.png'),
width: 300,
height: 300,
)),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _name,
decoration: InputDecoration(
hintText: "Full name",
icon: Icon(Icons.person_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The name field cannot be empty";
}
return null;
},
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
keyboardType: TextInputType.emailAddress,
controller: _email,
decoration: InputDecoration(
hintText: "Email",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Verify')),
icon: Icon(Icons.alternate_email),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(keyboardType: TextInputType.number,
controller: otp,
decoration: InputDecoration(
hintText: "otp",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Resend'),
),
icon: Icon(Icons.pin),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _password,
obscureText: hidePass,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(Icons.lock_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The password field cannot be empty";
} else if (value.length < 6) {
return "the password has to be at least 6 characters long";
}
return null;
},
),
trailing: IconButton(
icon: Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
hidePass = !hidePass;
});
}),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.pinkAccent,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
verifyOTP();
if (verified == true &&
_formKey.currentState.validate()) {
if (!await user.signUp(_name.text,
_email.text, _password.text)) {
// ignore: deprecated_member_use
_key.currentState.showSnackBar(
SnackBar(
content:
Text("Sign up failed")));
return;
}
changeScreenReplacement(
context, MyHomePage());
}
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Sign up",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"I already have an account",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black, fontSize: 16),
))),
],
)),
),
),
],
),
);
}
}
Error
I/flutter ( 5091): Email ID is valid
I/flutter ( 5091): --This error is from the package--
I/flutter ( 5091): FormatException: Unexpected character (at character 1)
I/flutter ( 5091): <!DOCTYPE html>
I/flutter ( 5091): ^
I/flutter ( 5091): --End package error message--
The error is coming from the package itself.
The endpoint that the package calls to send the OTP is down and so it returns an error page instead of the JSON the package expected. This causes an error in parsing the HTML which is why the error says:
FormatException: Unexpected character (at character 1)
<!DOCTYPE html>
^
I'll advise you to use a different service like firebase_auth for this or create an issue on the project.

Closure call with mismatched arguments: function '[]' error is being shown in flutter

In my program, this error comes in my laptop only. I typed the exact code as of the tutorial, but in tutorial, it is working fine, and i am getting this error -
Closure call with mismatched arguments: function '[]'
Receiver: Closure: () => Map<String, dynamic> from Function 'data':.
Tried calling: []("message")
Found: []() => Map<String, dynamic>
This is my code, in which error is coming. If you want full details of functions,
you can comment it out, and i will provide you the same in comments.
import 'package:flutter/material.dart';
import 'package:whatsapp/helper/constants.dart';
import 'package:whatsapp/services/database.dart';
import 'package:whatsapp/widget/widgets.dart';
class ConversationScreen extends StatefulWidget {
final String chatRoomId;
ConversationScreen(this.chatRoomId);
#override
_ConversationScreenState createState() => _ConversationScreenState();
}
class _ConversationScreenState extends State<ConversationScreen> {
DatabaseMethods databaseMethods = new DatabaseMethods();
TextEditingController messageController = new TextEditingController();
Stream chatMessageStream;
Widget ChatMessageList() {
return StreamBuilder(
stream: chatMessageStream,
builder: (context, snapshot){
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
return MessageTile(snapshot.data.documents[index].data["message"]);
},
);
},
);
}
sendMessage() {
if(messageController.text.isNotEmpty) {
Map<String, String> messageMap = {
"message" : messageController.text,
"sender" : Constants.myName,
};
databaseMethods.addConversationMessages(widget.chatRoomId, messageMap);
messageController.text = "";
}
}
#override
void initState() {
databaseMethods.getConversationMessages(widget.chatRoomId).then((value){
setState(() {
chatMessageStream = value;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Color(0xff1f1f1f),
appBar: appBarMain(context),
body: Container(
child: Stack(
children: [
ChatMessageList(),
Container(
alignment: Alignment.bottomCenter,
child: Container(
alignment: Alignment.bottomCenter,
padding: EdgeInsets.symmetric(horizontal: 5.0, vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: Container(
width: 300.0,
padding: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Color(0xff2D3D3C),
borderRadius: BorderRadius.circular(50.0),
),
child: TextField(
cursorColor: Color(0xff246e5d),
controller: messageController,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
),
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: 'Type a message',
hintStyle: TextStyle(
color: Colors.white54,
),
),
),
),
),
GestureDetector(
onTap: (){
sendMessage();
},
child: Padding(
padding: EdgeInsets.fromLTRB(8.0, 3.0, 1.0, 2.0),
child: Container(
height: 50.0,
width: 50.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xff246e5d),
),
child: Center(
child: Icon(
Icons.send,
color: Colors.white54,
size: 30.0,
),
),
),
),
),
],
),
),
),
],
),
),
),
);
}
}
class MessageTile extends StatelessWidget {
final String message;
MessageTile(this.message);
#override
Widget build(BuildContext context) {
return Container(
child: Text(
message,
style: TextStyle(
color: Colors.white,
),
),
);
}
}
DocumentSnapshot.data() is a method not a getter, therefore it's necessary to include the parentheses to actually call the method and obtain the returned Map. This is why dart is confused and throws an error as you're trying to use the [] operator on a function reference.
return MessageTile(snapshot.data.documents[index].data()["message"]);

Closure call with mismatched arguments: function '[]' in flutter

** I am getting this error**
Closure call with mismatched arguments: function '[]'
Receiver: Closure: (dynamic) => dynamic from Function 'get':.
Tried calling: []("url")
Found: [](dynamic) => dynamic
my code where I am receiving the data from firestore is this..
import 'package:flutter/material.dart';
import 'package:riyazat_quiz/services/database.dart';
import 'package:riyazat_quiz/views/create_quiz.dart';
import 'package:riyazat_quiz/widgets/widgets.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Stream quizStream;
DatabaseService databaseService = DatabaseService(); // this is to call the getQuizData() async{
return await FirebaseFirestore.instance.collection("Quiz").snapshots();
}
Widget quizList(){
return Container(
child: StreamBuilder(
stream:quizStream ,
builder: (context,snapshort){
return snapshort.data == null ? CircularProgressIndicator(): ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount : snapshort.data.documents.length ,
itemBuilder : (context,index){ return QuizTile(url:snapshort.data.documents[index].get['url'],
title:snapshort.data.documents[index].get['title'] ,
desc: snapshort.data.documents[index].get['desc'],);}
);
}
),
);
}
#override
void initState() {
databaseService.getQuizData().then((val){
setState(() {
quizStream =val;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: appBar(context),
),
backgroundColor: Colors.transparent,
elevation: 0.0,
brightness: Brightness.light,
),
body:
Column(
children: [
quizList(),
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CreateQuiz()));
},
),
],
),
);
}
}
class QuizTile extends StatelessWidget {
final String url,title,desc;
QuizTile({#required this.url,#required this.title,#required this.desc});
#override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: [
Image.network(url),
Container(
child: Column(
children: [
Text(title),
Text(desc),
],
),
)
],
),
);
}
}
can someone tell me where I am going wrong
ps: this is a quiz app where I am getting the data from the firestore,
using streams.
data saved on the firestore has three fields, "url", "title" "desc".
I want to retrieve them in the below widget and want to display them in a stack, but this error got me stuck in-between.
You need to do the following:
itemCount : snapshort.data.docs.length ,
itemBuilder : (context,index){
return QuizTile(url:snapshort.data.docs[index].data()['url'],
title:snapshort.data.docs[index].data()['title'] ,
desc: snapshort.data.docs[index].data()['desc'],
);
}
);
Since you are reference a collection, then you need to use docs which will retrieve a list of documents inside that collection:
https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/query_snapshot.dart#L18
Then to access each field in the document, you need to call data()
The answer by #Peter Haddad is correct. Just to highlight the difference with an example from my own code:
The previous version of code which created the same error:
snapshot.data.docs[index].data["chatRoomID"]
Updated version of code which solved the error:
snapshot.data.docs[index].data()["chatRoomID"]
Updated Version:
snapshot.data[i]['Email'],
Future getRequests() async {
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection("Buyer Requests").get();
return snapshot.docs;
}
body: FutureBuilder(
initialData: [],
future: getRequests(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
indexLength = snapshot.data.length;
if (snapshot.hasData)
return SizedBox(
child: PageView.builder(
itemCount: indexLength,
controller: PageController(viewportFraction: 1.0),
onPageChanged: (int index) => setState(() => _index = index),
itemBuilder: (_, i) {
return SingleChildScrollView(
child: Card(
margin: EdgeInsets.all(10),
child: Wrap(
children: <Widget>[
ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage(
'assets/images/shafiqueimg.jpeg'),
),
title: Text(
snapshot.data[i]['Email'],
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: Colors.black.withOpacity(0.7),
),
),
subtitle: Text(
snapshot.data[i]['Time'],
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(5)),
color: Colors.grey[200],
),
padding: EdgeInsets.all(10),
child: Text(
snapshot.data[i]['Description'],
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
),
SizedBox(
height: 8,
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(Icons.category_outlined),
title: Text(
'Category : ${snapshot.data[i]['Category']}',
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
),
),
SizedBox(height: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(Icons.location_pin),
title: Text(
snapshot.data[i]['Location'],
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
),
),
SizedBox(height: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(
Icons.attach_money,
color: kGreenColor,
),
title: Text(
'Rs.${snapshot.data[i]['Budget']}',
style: TextStyle(
fontSize: 14,
color: kGreenColor,
),
),
),
),
SizedBox(height: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(Icons.timer),
title: Text(
'Duration : ${snapshot.data[i]['Duration']}',
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
),
),
SizedBox(
height: 35,
),
RaisedButton(
padding: EdgeInsets.symmetric(vertical: 10),
child: Text('Send Offer'),
textColor: Colors.white,
color: Colors.green,
onPressed: () {
// Respond to button press
},
),
SizedBox(
height: 15,
),
Center(
child: Text(
"${i + 1}/$indexLength",
style: TextStyle(fontSize: 13),
),
),
],
),
),
],
),
),
);
},
),
);
else
return Center(
child: Text("Null"),
);
},
),
Given that you are referencing a collection, you must use docs to acquire a list of the documents included in that collection:
https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud firestore/cloud firestore/lib/src/query snapshot.dart#L18
then you must call data() in order to access each field in the document.

NoSuchMethodError: 'dart.global.firebase.auth' in the Flutter Chat App

I was creating this Chat App and after implementing the search function I encountered this NoSuchMethodError: tried to call a non-function, such as null: 'dart.global.firebase.auth' problem.
So basically now when I sign up the email and username doesn't get uploaded to firebase auth and Cloud Firestore, which earlier used to happen I think I did some mistake in the search.dart file which seems weird to me.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intro/helper/constants.dart';
import 'package:intro/services/database.dart';
import 'package:intro/widgets/widgets.dart';
import 'conversation_screen.dart';
class SearchScreen extends StatefulWidget {
#override
_SearchScreenState createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
DatabaseMethods databaseMethods = new DatabaseMethods();
TextEditingController searchTextEditingController =
new TextEditingController();
QuerySnapshot searchSnapshot;
Widget searchList() {
return searchSnapshot != null
? ListView.builder(
itemCount: searchSnapshot.docs.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return searchTile(
searchSnapshot.docs[index].data()["name"],
searchSnapshot.docs[index].data()["email"],
);
})
: Container();
}
initiateSearch() {
databaseMethods
.getUserByUsername(searchTextEditingController.text)
.then((val) {
setState(() {
searchSnapshot = val;
});
});
}
createChatroomAndStartConversation({String userName}) {
String chatRoomId = getChatRoomId(userName, Constants.myName);
List<String> users = [userName, Constants.myName];
Map<String, dynamic> chatRoomMap = {
"users": users,
"chatroomid": chatRoomId
};
DatabaseMethods().createChatRoom(chatRoomId, chatRoomMap);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ConversationScreen(),
));
}
Widget searchTile(String userName, String userEmail) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(userName, style: mediumTextStyle()),
Text(userEmail, style: mediumTextStyle())
],
),
Spacer(),
GestureDetector(
onTap: () {
createChatroomAndStartConversation(userName: userName);
},
child: Container(
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(30)),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Text(
"Message",
style: mediumTextStyle(),
),
),
)
],
),
);
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(context),
body: Container(
child: Column(
children: [
Container(
color: Color(0x54FFFFFF),
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(children: [
Expanded(
child: TextField(
controller: searchTextEditingController,
style: TextStyle(
color: Colors.white,
),
decoration: InputDecoration(
hintText: "Search Username",
hintStyle: TextStyle(
color: Colors.white54,
),
border: InputBorder.none),
),
),
GestureDetector(
onTap: () {
initiateSearch();
},
child: Container(
height: 35,
width: 35,
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
const Color(0x36FFFFFF),
const Color(0x0FFFFFFF)
]),
borderRadius: BorderRadius.circular(30)),
padding: EdgeInsets.all(1),
child: Icon(
Icons.search,
color: Colors.white,
)),
)
]),
),
searchList()
],
),
),
);
}
}
getChatRoomId(String a, String b) {
if (a.substring(0, 1).codeUnitAt(0) > b.substring(0, 1).codeUnitAt(0)) {
return "$b\_$a";
} else {
return "$a\_$b";
}
}
and just in case there is an error with the signUp.dart file here it is.
import 'package:flutter/material.dart';
import 'package:intro/helper/helperfunctions.dart';
import 'package:intro/services/auth.dart';
import 'package:intro/services/database.dart';
import 'package:intro/widgets/widgets.dart';
import 'chatRoomsScreen.dart';
class SignUp extends StatefulWidget {
final Function toggle;
SignUp(this.toggle);
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
bool isLoading = false;
AuthMethods authMethods = new AuthMethods();
DatabaseMethods databaseMethods = new DatabaseMethods();
final formKey = GlobalKey<FormState>();
TextEditingController userNameTextEditingController =
new TextEditingController();
TextEditingController emailTextEditingController =
new TextEditingController();
TextEditingController passwordTextEditingController =
new TextEditingController();
signMeUP() {
if (formKey.currentState.validate()) {
Map<String, String> userInfoMap = {
"name": userNameTextEditingController.text,
"email": emailTextEditingController.text,
};
HelperFunctions.saveUserEmailSharedPreference(
emailTextEditingController.text);
HelperFunctions.saveUserNameSharedPreference(
userNameTextEditingController.text);
setState(() {
isLoading = true;
});
authMethods
.signUpwithemailandpassword(emailTextEditingController.text,
passwordTextEditingController.text)
.then((value) {
// print("$value.uid");
databaseMethods.uploadUserInfo(userInfoMap);
HelperFunctions.saveUserLoggedInSharedPreference(true);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => ChatRoom()));
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(context),
body: isLoading
? Container(
child: Center(child: CircularProgressIndicator()),
)
: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height - 60,
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Form(
key: formKey,
child: Column(
children: [
TextFormField(
validator: (val) {
return val.isEmpty || val.length < 2
? "Invalid Username (Needs to be more than 2 characters)"
: null;
},
controller: userNameTextEditingController,
style: simpleTextStyle(),
decoration: textfieldInputDecoration("username"),
),
TextFormField(
validator: (val) {
return RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(val)
? null
: "Enter correct email";
},
controller: emailTextEditingController,
style: simpleTextStyle(),
decoration: textfieldInputDecoration("email"),
),
TextFormField(
obscureText: true,
validator: (val) {
return val.length < 6
? "Please provide with 6+ character"
: null;
},
controller: passwordTextEditingController,
style: simpleTextStyle(),
decoration: textfieldInputDecoration("password"),
),
],
),
),
SizedBox(
height: 10,
),
Container(
alignment: Alignment.centerRight,
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
"Forgot Password?",
style: simpleTextStyle(),
),
),
),
SizedBox(
height: 10,
),
GestureDetector(
onTap: () {
signMeUP();
},
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
const Color(0xff007EF4),
const Color(0xff2A75BC)
]),
borderRadius: BorderRadius.circular(30)),
child: Text("Sign Up", style: mediumTextStyle()),
),
),
SizedBox(
height: 10,
),
Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30)),
child: Text("Sign Up with Google",
style:
TextStyle(color: Colors.black, fontSize: 18)),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Already have an account? ",
style: mediumTextStyle(),
),
GestureDetector(
onTap: () {
widget.toggle();
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 8),
child: Text(
"Sign in now",
style: TextStyle(
color: Colors.white,
fontSize: 17,
decoration: TextDecoration.underline),
),
),
),
],
),
SizedBox(
height: 50,
)
],
),
),
),
),
);
}
}
And if there is any file anyone of you want: GitHub: Chat App
Because you Haven't initialize the method

Trying to access an instance of user. NoSuchMethod error when widget loads email = null. calling loggedInUser.email

Im calling a Firebase user email, i want to display user details on the screen. When widget loads, NoSuchMethod error displays and crashes app. Not sure where to go from here
import 'package:flutter/material.dart';
import 'package:simmanager/constaints.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class SettingScreen extends StatefulWidget {
#override
_SettingScreenState createState() => _SettingScreenState();
}
class _SettingScreenState extends State<SettingScreen> {
final _auth = FirebaseAuth.instance;
final _firestore = Firestore.instance;
FirebaseUser loggedInUser;
#override
void initState() {
getCurrentUser();
super.initState();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
}
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Settings'),
backgroundColor: primaryColor,
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(
Icons.edit,
color: Colors.black,
),
backgroundColor: secondaryColor,
),
body: SafeArea(
child: Container(
color: backgroundColor,
child: Column(
children: <Widget>[
Center(
child: Container(
margin: EdgeInsets.only(top: 20.0),
child: Icon(
Icons.account_circle,
size: 75.0,
color: primaryLight,
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 5.0,
color: Colors.grey[300],
spreadRadius: 5.0,
),
],
borderRadius: BorderRadius.circular(20.0),
),
padding: EdgeInsets.all(25.0),
child: Row(
children: <Widget>[
Container(
child: Text(
'Name: ',
style: TextStyle(fontSize: 16.0),
),
),
// TODO: add stream for user details
Container(
child: Text('Test'),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 5.0,
color: Colors.grey[300],
spreadRadius: 5.0,
),
],
borderRadius: BorderRadius.circular(20.0),
),
padding: EdgeInsets.all(25.0),
child: Row(
children: <Widget>[
Container(
child: Text(
'Email: ',
style: TextStyle(fontSize: 16.0),
),
),
// TODO: add stream for user details
Container(
child: Text(loggedInUser.email),
),
],
),
),
),
The following NoSuchMethodError was thrown building SettingScreen(dirty, state: _SettingScreenState#b9d92):
The getter 'email' was called on null.
Receiver: null
Tried calling: email
I've passed through it too. The way I managed so that I could fix the error was change the position of auth.currentUser() declaration. You probably have created your Auth auth inside the StatelessWidget.
Try to move the instance of Auth from StatelessWidget to your State, right before your void initState().

Resources