How can I use provider without context? - firebase

I have a widget where I use the provider but where I want to use the values is in normal widgets so maybe anyone can help.
This is where I use the provider :
Widget _buildName(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Full Name',
style: kLabelStyle3,
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
height: 50.0,
child: TextFormField(
initialValue: UserData.fullname;
validator: (val) => val.isEmpty ? 'Enter your Name' : null,
onChanged: (val) {
setState(() => _currentfullname = val);
},
style: TextStyle(
color: Colors.black,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.black,
width: 2.0,
),
),
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.person,
color: Colors.black,
),
hintText: 'Enter your Name',
hintStyle: kHintTextStyle2,
),
),
),
],
);
}
#override
Widget build(BuildContext context) {
final user = Provider.of<Userr>(context);
return StreamBuilder<UserData>(
stream: DatbaseService(uid:user.uid).userData,
builder: (context, snapshot) {
if(snapshot.hasData){
UserData userData =snapshot.data;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Form(
key: _formKey,
child: Stack(
children: <Widget>[
Container(
height: double.infinity,
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
padding: EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 10,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Stack(
children: [
Container(
width: 110,
height: 110,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
"https://images.pexels.com/photos/3307758/pexels-photo-3307758.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250",
))),
),
Positioned(
bottom: 0,
right: 0,
child: Container(
height: 35,
width: 35,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
width: 4,
color: Theme.of(context)
.scaffoldBackgroundColor,
),
color: Colors.green,
),
child: Icon(
Icons.edit,
color: Colors.white,
),
)),
],
),
),
SizedBox(
height: 10,
),
Text(
'Mein Profil',
style: TextStyle(
color: Colors.black,
fontFamily: 'OpenSans',
fontSize: 20.0,
fontWeight: FontWeight.w600,
),
),
showAlert2(),
_buildEmailTF(),
SizedBox(
height: 30.0,
),
_buildName(),
SizedBox(
height: 30.0,
),
_builduserName(),
SizedBox(
height: 30.0,
),
_buildPasswordTF(),
SizedBox(height: 30,),
_buildPassword2TF(),
_buildUpdateDataButton(),
// _buildEmailform(),
],
),
),
)
],
),
),
),
),
);
}else{
return null;
}
}
);
}
}
class DatbaseService{
final String uid;
DatbaseService({this.uid});
//collection reference
final CollectionReference myprofilsettings = FirebaseFirestore.instance.collection('meinprofilsettings');
Future updateUserData(String user,String fullname,String password,String email)async{
return await myprofilsettings.doc(uid).set({
'username':user,
'fullname':fullname,
'passwort':password,
'email':email,
});
}
//profil list from snapshot
List<myprofil> _myprofillistFromSnapshot(QuerySnapshot snapshot){
return snapshot.docs.map((doc){
return myprofil(
user: doc.data()['user']??'',
fullname: doc.data()['fullname']??'',
email: doc.data()['email']??'',
passowrd: doc.data()['password']??'',
);
}).toList();
}
//userData from snapshot
UserData _userDataFromSnapshot(DocumentSnapshot snapshot){
return UserData(
uid: uid,
name: snapshot.data()['name'],
fullname: snapshot.data()['fullname'],
email: snapshot.data()['email'],
password: snapshot.data()['password'],
);
}
//get myprofilsettings stream
Stream<List<myprofil>> get settings{
return myprofilsettings.snapshots().map(_myprofillistFromSnapshot);
}
//get user doc stream
Stream<UserData> get userData{
return myprofilsettings.doc(uid).snapshots().map(_userDataFromSnapshot);
}
}
import 'package:flutter/cupertino.dart';
class Userr{
final String uid;
Userr({this.uid});
}
class UserData {
final String uid;
final String user;
final String fullname;
final String email;
final String passowrd;
UserData({this.uid,this.user,this.fullname,this.email,this.passowrd, name, password});
Ignore this:
Because flutter says __it looks like It looks like your post is mostly code; please add some more details. ___
IM adding some textdehpkfnwrfemrjfikerfoiwnfdoiwjefiojnweoidfjwiodjwiojdoijweiodjweiojdoiewjdijewoijdoejwdiojewiojdiowjedijweoidjiowediwjdoiwejdiowjdiojwoidjaldknjlncjnnc xy,,y,y,,y,ykampkdnndendiowendiojweiopjdipqejkdpojkdposkqwpodkqopwkdopkqwopdskqopdkpoqwkdopqkwopdkqwpodkpoqkdpkqpodkpqkdpokdpo<skcpoaskdpoakdopkdpoekwopdkwepokdpowekdpokwepodkwepokdpowekdpowekpdkpekdpokeopdkpekdpowekdopewkpdkwpekdpwekdpowekdpowekdpowekdpkwepodkwepodkpoekdpoewkdpoekdp
======== Exception caught by widgets library =======================================================
The following assertion was thrown building StreamBuilder<UserData>(dirty, state: _StreamBuilderBaseState<UserData, AsyncSnapshot<UserData>>#c612d):
A build function returned null.
The offending widget is: StreamBuilder<UserData>
Build functions must never return null.
To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".
The relevant error-causing widget was:
StreamBuilder<UserData> file:///Users/name/StudioProjects/project/lib/seitenleiste/meinacount.dart:356:16
When the exception was thrown, this was the stack:
#0 debugWidgetBuilderValue.<anonymous closure> (package:flutter/src/widgets/debug.dart:305:7)
#1 debugWidgetBuilderValue (package:flutter/src/widgets/debug.dart:326:4)
#2 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4592:7)
#3 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4759:11)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================

I’m assuming that your _buildName() is a method of your widget and that you call it from you build method somewhere.
This means that you can pass either the context or the user into this method:
_buildName(BuildContext context) {} or _buildName(User user) {}
Try providing more of the code next time, specifically the parts where you call the method.
Edit after post update:
You need to have the user object in the buildName method so you cannot simply do UserData.fullname because UserData is a class not an instance.
So to get your data in the buildName you need to change it to:
_buildName(UserData userData) {
userData.fullname; // this now exists
}
And call is like: _buildName(userData)

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.

Undefined name 'firebase' Flutter

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 :)

Retrieving Data From Firestore in time

I have looked all over the internet for how to fix this problem and I can't find a solution anywhere. I am using flutter with firestore to make an app. I want to make it so when the user logins into the app at the top shows their name (simple right). I can get data from firestore:
Future<void> getName() async {
print("Attemping to get name!");
final firestoreInstance = await FirebaseFirestore.instance;
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
await firestoreInstance.collection("Users").doc(uid).get().then((value) {
print("Name: " + value.data()["firstName"]);
info.firstName=((value.data()["firstName"]));
})
class info {
static String firstName;
}
but it comes in too late so the app just says "Welcome back" As you can see here and not "Welcome back, Connor" As seen here
When I look in the console the function does run but the program doesn't wait for it and continues resulting in a null.
Thanks you
EDIT as requested UI code:
class Home extends StatelessWidget {
final DatabaseReference = FirebaseDatabase.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
static String firstName;
static String lastName;
static String email;
static String companyName;
static bool isNewAccount = false;
static String name = "Welcome back";
Home();
#override
Widget build(BuildContext context) {
final User user = auth.currentUser;
final uid = user.uid;
final ref = DatabaseReference.reference();
if (isNewAccount == true) {
userSetup(firstName, lastName, email, companyName);
isNewAccount = false;
}
getName(); //does get the name from the database but name will error out as it doesn't get the name fast enough (or that's what I think)
name= "Welcome back, "+info.firstName;
return WillPopScope(
onWillPop: () async => false,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.cyan,
body: SingleChildScrollView(
child: Container(
margin:
EdgeInsets.only(top: MediaQuery.of(context).size.height / 16),
child: Column(
children: [
Container(
margin: EdgeInsets.only(bottom: 10),
child: Text(
name,
textAlign: TextAlign.center,
style: new TextStyle(
color: Colors.white,
fontSize: MediaQuery.of(context).size.width / 16,
),
),
),
Container(
width: 260,
height: 125,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"CHECK-IN",
style: new TextStyle(
color: Colors.white,
fontSize: 40.0,
),
),
color: Colors.grey[850],
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Checkin()));
},
),
),
Container(
width: 260,
height: 140,
padding: EdgeInsets.only(top: 20),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"CHECK-OUT",
style: new TextStyle(
color: Colors.white,
fontSize: 38.0,
),
),
color: Colors.grey[850],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Checkout()));
},
),
),
Container(
margin: EdgeInsets.only(top: 55),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"Sign out: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"SIGN OUT",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
context.read<AuthenticationService>().signOut();
//return MyApp();
},
),
)
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"View Stats: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"STATS",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stats()));
},
),
),
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"View Profile: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"PROFILE",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stats()));*/
},
),
),
],
),
),
Container(
width: 240,
height: 55,
margin: EdgeInsets.only(
top: MediaQuery.of(context).size.height / 12),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"EMERGENCY REPORT",
style: new TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.grey[700],
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => EmergencyReport()));
},
),
),
],
),
),
),
),
),
);
}
static getAccountDetails(
String firstName1, String lastName1, String email1, String companyName1) {
firstName = firstName1;
lastName = lastName1;
email = email1;
companyName = companyName1;
isNewAccount = true;
}
static getFirstName(String nameFirst) {
name = "Welcome back, "+nameFirst;
}
}
FutureBuilder<DocumentSnapshot>(
future: firestoreInstance.collection("Users").doc(uid).get(),
builder: (_,snap){
return snap.hasData ? Text(snap.data.data()["firstName"]):CircularProgressIndicator();
},)
You need to convert StatelessWidget into StatefullWidget.
After that you have to write this in initState method
void initState() {
super.initState();
getName().then((){
setState(() {
name= "Welcome back, "+info.firstName;
});
});
}

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.

Resources