Roxox
Roxox

Reputation: 99

How can I get current user's information from Firebase to use it in my navbar - flutter

I'm trying to learn Flutter and developing some basic apps. The problem that I'm facing is that, I need to get the information from firebase of logged-in user and display s/he's name in my navbar. You can find my login-screen and navbar classes below. Can anyone help me how to get this information from firebase and use it in my code please?

login-screen.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:human_resources/screens/home.dart';
import 'package:human_resources/screens/registration-screen.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  //firebase
  final _auth = FirebaseAuth.instance;
  String? errorMessage;

  @override
  Widget build(BuildContext context) {
    final emailField = TextFormField(
        autofocus: false,
        controller: emailController,
        keyboardType: TextInputType.emailAddress,
        validator: (value) {
          if (value!.isEmpty) {
            return ("Please Enter Your Email");
          }
          //reg expression for email validation
          if (!RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]")
              .hasMatch(value)) {
            return ("Please Enter a Valid Email");
          }
          return null;
        },
        onSaved: (value) {
          emailController.text = value!;
        },
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          prefixIcon: const Icon(Icons.mail),
          contentPadding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
          hintText: "Email",
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
        ));

    final passwordField = TextFormField(
        autofocus: false,
        controller: passwordController,
        obscureText: true,
        validator: (value) {
          RegExp regex = RegExp(r'^.{6,}$');
          if (value!.isEmpty) {
            return ("Password is Required for Login");
          }
          if (!regex.hasMatch(value)) {
            return ("Enter Valid Password(Min. 6 Character)");
          }
          return null;
        },
        onSaved: (value) {
          passwordController.text = value!;
        },
        textInputAction: TextInputAction.done,
        decoration: InputDecoration(
          prefixIcon: const Icon(Icons.vpn_key),
          contentPadding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
          hintText: "Password",
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
        ));

    final loginButton = Material(
        elevation: 5,
        borderRadius: BorderRadius.circular(30),
        color: Colors.blueAccent,
        child: MaterialButton(
          padding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
          minWidth: MediaQuery.of(context).size.width,
          onPressed: () {
            signIn(emailController.text, passwordController.text);
          },
          child: const Text(
            "Login",
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 20,
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
        ));

    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: SingleChildScrollView(
          child: Container(
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(36.0),
              child: Form(
                key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    SizedBox(
                        height: 200,
                        child: Image.asset(
                          "logo.png",
                          fit: BoxFit.contain,
                        )),
                    const SizedBox(
                      height: 45,
                    ),
                    emailField,
                    const SizedBox(
                      height: 25,
                    ),
                    passwordField,
                    const SizedBox(
                      height: 36,
                    ),
                    loginButton,
                    const SizedBox(
                      height: 15,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        const Text("Don't have an account? "),
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        const RegistrationScreen()));
                          },
                          child: const Text(
                            "SignUp",
                            style: TextStyle(
                                color: Colors.blueAccent,
                                fontWeight: FontWeight.bold,
                                fontSize: 15),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void signIn(String email, String password) async {
    if (_formKey.currentState!.validate()) {
      try {
        await _auth
            .signInWithEmailAndPassword(email: email, password: password)
            .then((uid) => {
                  Fluttertoast.showToast(msg: "Login Successful"),
                  Navigator.of(context).pushReplacement(
                      MaterialPageRoute(builder: (context) => const MyHomePage())),
                });
      } on FirebaseAuthException catch (error) {
        switch (error.code) {
          case "invalid-email":
            errorMessage = "Your email address appears to be malformed.";
            break;
          case "wrong-password":
            errorMessage = "Your password is wrong.";
            break;
          case "user-not-found":
            errorMessage = "User with this email doesn't exist.";
            break;
          case "user-disabled":
            errorMessage = "User with this email has been disabled.";
            break;
          case "too-many-requests":
            errorMessage = "Too many requests";
            break;
          case "operation-not-allowed":
            errorMessage = "Signing in with Email and Password is not enabled.";
            break;
          default:
            errorMessage = "An undefined Error happened.";
        }
        Fluttertoast.showToast(msg: errorMessage!);
        // ignore: avoid_print
        print(error.code);
      }
    }
  }
}

home.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'navbar.dart';
import '../model/user_model.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  User? user = FirebaseAuth.instance.currentUser;
  UserModel loggedInUser = UserModel();

  @override
  void initState() {
    super.initState();
    FirebaseFirestore.instance
        .collection("users")
        .doc(user!.uid)
        .get()
        .then((value) {
      loggedInUser = UserModel.fromMap(value.data());
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: NavBar(),
      appBar: AppBar(
        title: const Text("Anasayfa"),
      ),
      body: const Center(),
    );
  }
}

navbar.dart

import 'package:flutter/material.dart';

class NavBar extends StatelessWidget {
  const NavBar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          UserAccountsDrawerHeader(
            accountName: const Text("Test"),
            accountEmail: const Text("Test"),
            currentAccountPicture: CircleAvatar(
              child: ClipOval(
                child: Image.network(
                  'https://sunrift.com/wp-content/uploads/2014/12/Blake-profile-photo-square.jpg',
                  width: 90,
                  height: 90,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            decoration: const BoxDecoration(
                color: Colors.blue,
                image: DecorationImage(
                  image: NetworkImage(
                    "https://blog.depositphotos.com/wp-content/uploads/2017/07/Soothing-nature-backgrounds-2.jpg.webp",
                  ),
                  fit: BoxFit.cover,
                )),
          ),
          ListTile(
            leading: const Icon(Icons.home),
            title: const Text("Anasayfa"),
            // ignore: avoid_returning_null_for_void
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.people),
            title: const Text("Kullanıcılar"),
            // ignore: avoid_returning_null_for_void
            onTap: () => null,
          ),
          ExpansionTile(
            leading: const Icon(Icons.document_scanner_rounded),
            title: const Text('Raporlar'),
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.document_scanner_outlined),
                  title: const Text('Günlük Rapor'),
                  // ignore: avoid_returning_null_for_void
                  onTap: () => null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.document_scanner_outlined),
                  title: const Text('Haftalık Rapor'),
                  // ignore: avoid_returning_null_for_void
                  onTap: () => null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.document_scanner_outlined),
                  title: const Text('Aylık Rapor'),
                  // ignore: avoid_returning_null_for_void
                  onTap: () => null,
                ),
              ),
            ],
          ),
          ExpansionTile(
            leading: const Icon(Icons.question_answer),
            title: const Text('Talepler'),
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.question_answer_outlined),
                  title: const Text('İzin Talepleri'),
                  // ignore: avoid_returning_null_for_void
                  onTap: () => null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.request_page_outlined),
                  title: const Text('Avans Talepleri'),
                  // ignore: avoid_returning_null_for_void
                  onTap: () => null,
                ),
              ),
            ],
          ),
          ListTile(
            leading: const Icon(Icons.track_changes),
            title: const Text("Mesai Takip"),
            // ignore: avoid_returning_null_for_void
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.notifications),
            title: const Text("Duyuru Ekle"),
            // ignore: avoid_returning_null_for_void
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.person),
            title: const Text("Profil"),
            // ignore: avoid_returning_null_for_void
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.exit_to_app),
            title: const Text("Exit"),
            // ignore: avoid_returning_null_for_void
            onTap: () => null,
          ),
        ],
      ),
    );
  }
}

user_model.dart

class UserModel {
  String? uid;
  String? email;
  String? firstName;
  String? secondName;

  UserModel({this.uid, this.email, this.firstName, this.secondName});

  // receiving data from server
  factory UserModel.fromMap(map) {
    return UserModel(
      uid: map['uid'],
      email: map['email'],
      firstName: map['firstName'],
      secondName: map['secondName'],
    );
  }

  // sending data to our server
  Map<String, dynamic> toMap() {
    return {
      'uid': uid,
      'email': email,
      'firstName': firstName,
      'secondName': secondName,
    };
  }
}

user_model.dart

class UserModel {
  String? uid;
  String? email;
  String? firstName;
  String? secondName;

  UserModel({this.uid, this.email, this.firstName, this.secondName});

  // receiving data from server
  factory UserModel.fromMap(map) {
    return UserModel(
      uid: map['uid'],
      email: map['email'],
      firstName: map['firstName'],
      secondName: map['secondName'],
    );
  }

  // sending data to our server
  Map<String, dynamic> toMap() {
    return {
      'uid': uid,
      'email': email,
      'firstName': firstName,
      'secondName': secondName,
    };
  }
}

Upvotes: 0

Views: 654

Answers (2)

Sheetal Savani
Sheetal Savani

Reputation: 1428

You can do this using https://pub.dev/packages/get_storage

First of all in main.dart initialize the preference

GetStorage getPreference = GetStorage();

pref() async {
 await GetStorage.init();
}

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 pref();
 runApp(const MyApp());
}

///Your code here

After login store your user image in the preference using

getPreference.write("LoginUserModel", json.encode(value));

Now in navbar init Read that preference using

json.decode(getPreference.read("LoginUserModel"));

and to encode with JSON

If you are using getX

 Rx<UserModel> userModel = UserModel().obs;
 userModel.value = UserModel.fromJson(json.decode(getPreference.read("LoginUserModel")));

or

UserModel userModel = UserModel();
userModel = UserModel.fromJson(json.decode(getPreference.read("LoginUserModel")));
  • now you can use the userModel.userInformation ex: (userModel.email)

Upvotes: 0

Ravin Laheri
Ravin Laheri

Reputation: 822

Set this after successful login,

getPreference.write("UserData",FirebaseAuth.instance.currentUser);

getPreference is variable of local storage.

Store this in Preference Either in GetStorage or SharedPreference after login.

Create model as per Firebase Data of user for that you can use https://ashamp.github.io/jsonToDartModel/

class LoginModelDataUser {

  String? Id;
  int? role;
  String? firstName;
  String? lastName;
  String? mobile;
  String? postcode;
  String? email;
  String? otptoforgotpass;
  String? profileimageurl;
  String? backgroundProfileimageurl;
  String? address1;
  String? address2;
  String? state;
  String? city;
  bool? active;
  bool? phoneVerified;
  bool? emailVerified;
  int? V;
  String? id;

  LoginModelDataUser({
    this.Id,
    this.role,
    this.firstName,
    this.lastName,
    this.mobile,
    this.postcode,
    this.email,
    this.otptoforgotpass,
    this.profileimageurl,
    this.backgroundProfileimageurl,
    this.address1,
    this.address2,
    this.state,
    this.city,
    this.active,
    this.phoneVerified,
    this.emailVerified,
    this.V,
    this.id,
  });
  LoginModelDataUser.fromJson(Map<String, dynamic> json) {
    Id = json['_id']?.toString();
    role = json['role']?.toInt();
    firstName = json['firstName']?.toString();
    lastName = json['lastName']?.toString();
    mobile = json['mobile']?.toString();
    postcode = json['postcode']?.toString();
    email = json['email']?.toString();
    otptoforgotpass = json['otptoforgotpass']?.toString();
    profileimageurl = json['profileimageurl']?.toString();
    backgroundProfileimageurl = json['backgroundProfileimageurl']?.toString();
    address1 = json['address1']?.toString();
    address2 = json['address2']?.toString();
    state = json['state']?.toString();
    city = json['city']?.toString();
    active = json['active'];
    phoneVerified = json['phoneVerified'];
    emailVerified = json['emailVerified'];
    V = json['__v']?.toInt();
    id = json['id']?.toString();
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['_id'] = Id;
    data['role'] = role;
    data['firstName'] = firstName;
    data['lastName'] = lastName;
    data['mobile'] = mobile;
    data['postcode'] = postcode;
    data['email'] = email;
    data['otptoforgotpass'] = otptoforgotpass;
    data['profileimageurl'] = profileimageurl;
    data['backgroundProfileimageurl'] = backgroundProfileimageurl;
    data['address1'] = address1;
    data['address2'] = address2;
    data['state'] = state;
    data['city'] = city;
    data['active'] = active;
    data['phoneVerified'] = phoneVerified;
    data['emailVerified'] = emailVerified;
    data['__v'] = V;
    data['id'] = id;
    return data;
  }
}


Rx<LoginModelDataUser> userData = LoginModelDataUser().obs;

kAuthController.userData.value = LoginModelDataUser.fromJson(getPreference.read("UserData"));

Use it in widget

Image.Network(kAuthController.userData.value.profileimageurl??"");

Upvotes: 3

Related Questions