having an issue connecting with authentication with Firebase and Flutter - firebase

I'm trying to verify the connection with Google account and Email with no success.
I'm not sure if it is a problem with versions of Dependency even though I have checked it in the net for few times or it is something with my code that isn't correct
app.gradle
implementation 'com.google.firebase:firebase-auth:19.1.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
gradle
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:authentication/ui/home.dart';
import 'package:authentication/ui/login.dart';
import 'package:authentication/ui/splash.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MainScreen(),
);
}
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (context,AsyncSnapshot<FirebaseUser> snapshot) {
if(snapshot.connectionState == ConnectionState.waiting)
return SplashPage();
if(!snapshot.hasData || snapshot.data == null)
return LoginPage();
return LoginPage();
},
);
}
}
firebase util
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthProvider {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<bool> signInWithEmail(String email, String password) async{
try {
AuthResult result = await _auth.signInWithEmailAndPassword(email: email,password: password);
FirebaseUser user = result.user;
if(user != null)
return true;
else
return false;
} catch (e) {
return false;
}
}
Future<void> logOut() async {
try {
await _auth.signOut();
} catch (e) {
print("error logging out");
}
}
Future<bool> loginWithGoogle() async {
try {
GoogleSignIn googleSignIn = GoogleSignIn();
GoogleSignInAccount account = await googleSignIn.signIn();
if(account == null )
return false;
AuthResult res = await _auth.signInWithCredential(GoogleAuthProvider.getCredential(
idToken: (await account.authentication).idToken,
accessToken: (await account.authentication).accessToken,
));
if(res.user == null)
return false;
return true;
} catch (e) {
print(e.toString());
return false;
}
}
}
splash
import 'package:flutter/material.dart';
class SplashPage extends StatelessWidget {
#override
Widget build(BuildContext context){
return Scaffold(
body: Container(
color: Theme.of(context).primaryColor,
child: SafeArea(
child: Container(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(
backgroundColor: Colors.white,
),
const SizedBox(height: 10.0),
Text("Loading", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
fontSize: 18.0
),),
],
),
),
),
),
);
}
}
login
import 'package:authentication/utils/firebase_auth.dart';
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
TextEditingController _emailController;
TextEditingController _passwordController;
#override
void initState() {
super.initState();
_emailController = TextEditingController(text: "");
_passwordController = TextEditingController(text: "");
}
#override
Widget build(BuildContext context){
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 100.0),
Text("Login", style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0
),),
const SizedBox(height: 20.0),
RaisedButton(
child: Text("Login with Google"),
onPressed: () async {
bool res = await AuthProvider().loginWithGoogle();
if(!res)
print("error logging in with google");
},
),
TextField(
controller: _emailController,
decoration: InputDecoration(
hintText: "Enter email"
),
),
const SizedBox(height: 10.0),
TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
hintText: "Enter password"
),
),
const SizedBox(height: 10.0),
RaisedButton(
child: Text("Login"),
onPressed: ()async {
if(_emailController.text.isEmpty || _passwordController.text.isEmpty) {
print("Email and password cannot be empty");
return;
}
bool res = await AuthProvider().signInWithEmail(_emailController.text, _passwordController.text);
if(!res) {
print("Login failed");
}
},
)
],
),
),
),
);
}
}
home
import 'package:authentication/utils/firebase_auth.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Home page"),
RaisedButton(
child: Text("Log out"),
onPressed: (){
AuthProvider().logOut();
},
)
],
),
),
);
}
}
Log while trying to connect via email and google account
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device Android SDK built for x86...
D/EGL_emulation(12507): eglMakeCurrent: 0x9d385540: ver 2 0 (tinfo 0x9d383480)
D/EGL_emulation(12507): eglMakeCurrent: 0xa67b2940: ver 2 0 (tinfo 0x86e94740)
I/zygote (12507): Do partial code cache collection, code=29KB, data=21KB
I/zygote (12507): After code cache collection, code=28KB, data=21KB
I/zygote (12507): Increasing code cache capacity to 128KB
D/EGL_emulation(12507): eglMakeCurrent: 0xa67b2940: ver 2 0 (tinfo 0x86e94740)
I/flutter (12507): PlatformException(exception, Unknown, null)
I/flutter (12507): error logging in with google
D/EGL_emulation(12507): eglMakeCurrent: 0xa67b2940: ver 2 0 (tinfo 0x86e94740)
I/zygote (12507): Do partial code cache collection, code=61KB, data=42KB
I/zygote (12507): After code cache collection, code=60KB, data=42KB
I/zygote (12507): Increasing code cache capacity to 256KB
I/BiChannelGoogleApi(12507): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzao#d9d6493
D/FirebaseAuth(12507): Notifying id token listeners about user ( LnyMICjEyJNjtqKlCo5Qd8gAqva2 ).

Related

Can't use email with a password to create a user in the Firebase console

My program runs successfully without bug.
After the virtual machine enters the email and password
first:
click the Register button without jumping to the next page
second:
return to the User tab of the authentication page, , which shows in the Firebase console that this project does not currently have users.
I don't know what went wrong
this is my registrationScreen code
import 'package:flutter/material.dart';
import 'chat_screen.dart';
import 'package:flutter_application_3_vs/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
class RegistrationScreen extends StatefulWidget {
static const String id = "registration_screen";
#override
_RegistrationScreenState createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
late String email;
late String password;
final FirebaseAuth _auth = FirebaseAuth.instance;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 65, 110, 132),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Hero(
tag: "logo",
child: SizedBox(
height: 200,
child: Image.asset('images/logo.png'),
),
),
const SizedBox(
height: 48.0,
),
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
email = value;
},
decoration: kTextFeidDecoration.copyWith(hintText: "input email"),
),
const SizedBox(
height: 8.0,
),
TextField(
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
password = value;
},
decoration: kTextFeidDecoration.copyWith(hintText: "input password"),
),
const SizedBox(
height: 24.0,
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Material(
color: Colors.blueAccent,
borderRadius: const BorderRadius.all(Radius.circular(30.0)),
elevation: 5.0,
child: MaterialButton(
onPressed: () async {
try {
final newUser =
(await _auth.createUserWithEmailAndPassword(
email: email, password: password))
.user;
if (newUser != null) {
Navigator.pushNamed(context, ChatScreen.id);
}
} catch (e) {
print(e);
}
},
when I run is the output of my vscode debugging console
D/InputMethodManager( 2095): showSoftInput() view=io.flutter.embedding.android.FlutterView{e5f1730 VFE...... .F...... 0,0-1080,2208 #1 aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
D/InsetsController( 2095): show(ime(), fromIme=true)
D/InputMethodManager( 2095): showSoftInput() view=io.flutter.embedding.android.FlutterView{e5f1730 VFE...... .F...... 0,0-1080,2208 #1 aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
D/InsetsController( 2095): show(ime(), fromIme=true)
D/InputMethodManager( 2095): showSoftInput() view=io.flutter.embedding.android.FlutterView{e5f1730 VFE...... .F...... 0,0-1080,2208 #1 aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
D/InsetsController( 2095): show(ime(), fromIme=true)
D/EGL_emulation( 2095): app_time_stats: avg=314.21ms min=56.71ms max=496.93ms count=4
D/InputMethodManager( 2095): showSoftInput() view=io.flutter.embedding.android.FlutterView{e5f1730 VFE...... .F...... 0,0-1080,2208 #1 aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
D/InsetsController( 2095): show(ime(), fromIme=true)
D/EGL_emulation( 2095): app_time_stats: avg=370.18ms min=118.62ms max=500.19ms count=3
W/System ( 2095): Ignoring header X-Firebase-Locale because its value was null.
D/EGL_emulation( 2095): app_time_stats: avg=371.83ms min=119.00ms max=500.65ms count=3
2
W/System ( 2095): Ignoring header X-Firebase-Locale because its value was null.
D/EGL_emulation( 2095): app_time_stats: avg=29.69ms min=10.27ms max=330.47ms count=34
This is the firebase dependency in my pubspec.yaml file
firebase_core: ^1.16.0
firebase_auth: ^3.3.17
cloud_firestore: ^3.1.13``
this is my mian.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'screens/registration_screen.dart';
import 'screens/chat_screen.dart';
import 'screens/login_screen.dart';
import "screens/welcome.dart";
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const FlashChat());
}
class FlashChat extends StatelessWidget {
const FlashChat({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
textTheme: const TextTheme(
bodyText1: TextStyle(color: Color.fromRGBO(237, 225, 225, 0.533)),
),
),
initialRoute: WelcomeScreen.id,
routes: {
WelcomeScreen.id: (context) => const WelcomeScreen(),
LoginScreen.id: (context) => LoginScreen(),
RegistrationScreen.id: (context) => RegistrationScreen(),
ChatScreen.id: (context) => const ChatScreen(),
},

The following FirebaseException was thrown building Builder: [core/no-app] No Firebase App '[DEFAULT]' has been created- call Firebase.initializeApp()

I tried all the solutions that are previously present on stackoverflow nothing is working , I am trying from some days but each time i stuck here.
please give me a solution for this
Thanks
This is my code in flutter .....
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'firstpage.dart';
import 'package:firebase_core/firebase_core.dart';
void main(){
runApp(MaterialApp(
home: Homepage(),
routes: {
'/home':(context){
return Homepage();
},
'/first':(context){
return First_Page();
}
},
));
}
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
final _auth= FirebaseAuth.instance;
final _user=TextEditingController();
final _pass=TextEditingController();
String email='';
String password='';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text(
'Sign-Up',
),
centerTitle: true,
),
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: EdgeInsets.only(top: 250),
),
Container(
child: TextFormField(
controller: _user,
decoration: InputDecoration(
hintText: "Email-id",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
),
),
),
SizedBox(height: 10,),
Container(
child: TextFormField(
controller: _pass,
decoration: InputDecoration(
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
),
),
),
FlatButton(
color: Colors.blue,
child: Text('Sign-up'),
onPressed: () async {
await Firebase.initializeApp();
email=_user.toString();
password=_pass.toString();
try{
final newuser= await _auth.createUserWithEmailAndPassword(email: email, password:
password);
if(newuser!=null){
Navigator.pushNamed(context, '/First_Page');
}
}
catch(e){
print('error');
}
},
),
],
),
),
);
}
}
These following are the dependencies in my pubsppec.yaml
dependencies:
flutter:
sdk: flutter
firebase_auth: ^3.2.0
firebase_core :
======== Exception caught by widgets library =======================================================
The following FirebaseException was thrown building Builder:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
1.initialize your firebase before the run app like this
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
You should not use home: if you are using routes:
void main(){
runApp(MaterialApp(
home: Homepage(), // <== remove this line
routes: {
'/':(context){ // <== change to this
return Homepage();
},
'/first':(context){
return First_Page();
}
},
));
}

Flutter Firebase App goes to Waiting Connection State when hot-reloaded

I have a Flutter application running through VS Code which does simple authentication using Firebase. Following is my full program.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
import 'package:fireauth_starter/views/home_view.dart';
import 'views/login_page_view.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(FireAuthStarter());
}
class FireAuthStarter extends StatelessWidget {
//final Future<FirebaseApp> _initialisation = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
//
return Provider<FirebaseAuth>(
create: (context) => FirebaseAuth.instance,
child: MaterialApp(
title: 'Firebase Authentication',
home: LandingPage(),
),
);
}
}
class LandingPage extends StatelessWidget {
const LandingPage();
#override
Widget build(BuildContext context) {
final firebaseAuth = Provider.of<FirebaseAuth>(context);
return StreamBuilder<User>(
stream: firebaseAuth.authStateChanges(),
builder: (context, AsyncSnapshot<User> snapshot) {
print(snapshot.connectionState.toString());
if (snapshot.connectionState == ConnectionState.active) {
//final bool signedIn = snapshot.hasData;
User user = snapshot.data;
return user == null ? LoginPageView() : HomeView();
//return signedIn ? DashBoard() : FirstView();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
});
}
}
class LoginPageView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final firebaseAuth = Provider.of<FirebaseAuth>(context);
return MaterialApp(
home: Center(
child: Container(
child: TextButton(
child: Text('Sign In'),
onPressed: () {
firebaseAuth.signInWithEmailAndPassword(
email: 'myemail#email.com',
password: '1234567',
);
},
),
),
),
);
}
}
class HomeView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final firebaseAuth = Provider.of<FirebaseAuth>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Home View'),
actions: [
TextButton(
child: Text('Sign Out'),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
),
onPressed: () {
firebaseAuth.signOut();
},
),
],
),
body: Center(
child: Container(child: Text('Home View content')),
),
),
);
}
}
The application works as expected but when I use hot reload or hot restart, app get stuck in Progress Indicator because the snapshot.connectionState returns 'ConnectionState.waiting'
https://api.flutter.dev/flutter/widgets/ConnectionState-class.html states waiting: indicating that the asynchronous operation has begun, typically with the data being null.
I though the hot restart will reset all the states and app will perform as initial load. But it doesn't. What am I missing in this?

How to save user data in cloud fire store in flutter

I am using a package called lit_firebase_auth which makes firebase authentication easier to handle. I want to be able to save user data, such as the username after the user logs in. Basically as such:
User logs in or signs up --> User clicks on edit profile page from the home screen --> User can enter their desired name in the text field and click save --> Saves this data to the cloud of the respectful logged in user.
Please I'm a beginner and I have no idea how to pull this off.
Here is the code for reference:
cloud_firebase.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<void> userSetup(String displayName) async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
users.add({'displayName': displayName, 'uid': uid});
return;
}
auth.dart
import 'package:flutter/material.dart';
import 'package:kiwi/screens/auth/register.dart';
import 'package:kiwi/screens/background_painter.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/auth/sign_in.dart';
import 'package:animations/animations.dart';
import 'package:kiwi/screens/home.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const AuthScreen(),
);
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen>
with SingleTickerProviderStateMixin {
AnimationController _controller;
ValueNotifier<bool> showSignInPage = ValueNotifier<bool>(true);
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: LitAuth.custom(
onAuthSuccess: () {
Navigator.of(context).pushReplacement(HomeScreen.route);
},
child: Stack(
children: [
SizedBox.expand(
child: CustomPaint(
painter: BackgroundPainter(),
)),
Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800),
child: ValueListenableBuilder<bool>(
valueListenable: showSignInPage,
builder: (context, value, child) {
return PageTransitionSwitcher(
reverse: !value,
duration: Duration(milliseconds: 800),
transitionBuilder:
(child, animation, secondaryAnimation) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
fillColor: Colors.transparent,
child: child,
);
},
child: value
? SignIn(
key: ValueKey('SignIn'),
onRegisterClicked: () {
context.resetSignInForm();
showSignInPage.value = false;
_controller.forward();
},
)
: Register(
key: ValueKey('Register'),
onSignInPressed: () {
context.resetSignInForm();
showSignInPage.value = true;
_controller.reverse();
},
),
);
},
),
),
),
],
),
),
);
}
}
splash.dart
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/home.dart';
import 'package:kiwi/screens/auth/auth.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const SplashScreen(),
);
#override
Widget build(BuildContext context) {
final user = context.watchSignedInUser();
user.map(
(value) {
_navigateToHomeScreen(context);
},
empty: (_) {
_navigateToAuthScreen(context);
},
initializing: (_) {},
);
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
void _navigateToAuthScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(AuthScreen.route),
);
}
void _navigateToHomeScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(HomeScreen.route),
);
}
}
edit_profile.dart
import 'package:flutter/material.dart';
import 'package:kiwi/config/palette.dart';
import 'package:kiwi/screens/auth/decoration_functions.dart';
class Profile extends StatefulWidget {
const Profile({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const Profile(),
);
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
// UserModel _currentUser = locator.get<UserController>().currentUser;
// File _image;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Edit Profile'),
),
body: Builder(
builder: (context) => Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Column(
children: <Widget>[
Text(
'Hey there',
style: TextStyle(color: Palette.lightGreen, fontSize: 20),
)
],
),
SizedBox(
height: 20,
),
Expanded(
flex: 8,
child: ListView(
children: [
Padding(
padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
child: TextFormField(
style: const TextStyle(
fontSize: 18,
color: Colors.green,
),
decoration: signInInputDecoration(
hintText: 'New Username',
),
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
elevation: 4,
color: Colors.red,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
),
RaisedButton(
elevation: 4,
color: Palette.lightGreen,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Save',
style: TextStyle(color: Colors.white),
),
),
],
),
],
),
),
],
),
),
),
);
}
}
to save user data to document in firebase using uuid for document name the below code will work.
if you are confused about how to use the code in your app its simple.
just follow the steps:
call userSetup Function from onpress while passing the display name data.
how to use
the below code will create new document using the currect users uuid in firestore in user collection and save the data.
onPress:(){
userSetup(displayName:"zakriakhan");
}
userSteup Function
Future<void> userSetup(String displayName) async {
//firebase auth instance to get uuid of user
FirebaseAuth auth = FirebaseAuth.instance.currentUser();
//now below I am getting an instance of firebaseiestore then getting the user collection
//now I am creating the document if not already exist and setting the data.
FirebaseFirestore.instance.collection('Users').document(auth.uid).setData(
{
'displayName': displayName, 'uid': uid
})
return;
}

The getter 'email' was called on null

I'm trying to make a chat between two people using Flutter and Firebase but I'm facing an error when I connect into my app using Firebase's signInWithEmailAndPassword, it tells me:
The getter 'email' was called on null. Receiver: null Tried calling:
email
And Flutter also tells me the error come from the MaterialApp widget from my main.dart which doesn't help me to find the error..
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:social/responsive/size_config.dart';
import 'settings.dart';
import 'home.dart';
final _firestore = Firestore.instance;
FirebaseUser loggedInUser;
class ActivityFeed extends StatefulWidget {
static const String id = 'activity_feed_screen';
#override
_ActivityFeedState createState() => _ActivityFeedState();
}
class _ActivityFeedState extends State<ActivityFeed> {
final _auth = FirebaseAuth.instance;
#override
void initState() {
super.initState();
getCurrentUser();
}
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(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Container(
color: Colors.red,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
UserInfo(),
FlatButton(
child: Icon(
Icons.settings,
color: Colors.white,
),
onPressed: () {
Navigator.pushNamed(context, Settings.id);
},
),
FlatButton(
child: Icon(
Icons.not_interested,
color: Colors.white,
),
onPressed: () {
_auth.signOut();
Navigator.pushNamed(context, Home.id);
},
),
],
),
),
)
],
),
);
}
}
class UserInfo extends StatefulWidget {
#override
_UserInfoState createState() => _UserInfoState();
}
class _UserInfoState extends State<UserInfo> {
String email = loggedInUser.email;
String username;
#override
void initState() {
super.initState();
getUsername();
}
void getUsername() async {
DocumentReference docRef = _firestore.collection('users').document(email);
docRef.get().then((snapshot) {
if (snapshot.exists) {
username = snapshot.data['username'];
}
});
}
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Column(
children: <Widget>[
Text(
'Welcome $username',
style: TextStyle(
fontFamily: 'Amatic',
fontSize: SizeConfig.safeBlockHorizontal * 10),
),
],
)
;
}
}
So basically what I am just trying to display 'Welcome' + the username, but it doesn't want,
my Firebase Database have one collection named 'users', where the document names are the email the user used when he created his account.
All the Register/Log-In process seems to work fine.
If someone has a clue of what is happening that would be awesome, thanks.
You initialize username as null. You can either check it on the widget tree
username != null ? Text(
'Welcome $username',
style: TextStyle(
fontFamily: 'Amatic',
fontSize: SizeConfig.safeBlockHorizontal * 10),
) : CircularProgressIndicator()
and set it via setState()
setState(() {
username = snapshot.data['username'];
});
Another solution is to change
String username;
to
String username = '';
You should use a state management method by the way. setState() is very primitive and you will end up having sphagetti code if you use it as a state management solution.

Resources