繁体   English   中英

如何从颤振中获取当前用户的信息以在我的导航栏中使用它

[英]How can I get current user's information from flutter to use it in my navbar

我正在尝试学习 Flutter 并开发一些基本的应用程序。 我面临的问题是,我需要从登录用户的 firebase 获取信息并在我的导航栏中显示他/她的名字。 您可以在下面找到我的登录屏幕和导航栏类。 谁能帮助我如何从firebase获取这些信息并在我的代码中使用它?

登录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);
      }
    }
  }
}

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

导航栏.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,
    };
  }
}

登录成功后设置此项,

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

getPreference 是本地存储的变量。

登录后将其存储在GetStorageSharedPreference中。

根据用户的 Firebase 数据创建模型,您可以使用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"));

在小部件中使用它

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

您可以使用https://pub.dev/packages/get_storage执行此操作

首先在 main.dart 中初始化首选项

GetStorage getPreference = GetStorage();

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

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

///你的代码在这里

登录后将您的用户图像存储在首选项中

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

现在在 navbar init 中使用

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

并用 JSON 编码

如果您使用的是 getX

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

或者

UserModel userModel = UserModel();
userModel = UserModel.fromJson(json.decode(getPreference.read("LoginUserModel")));
  • 现在您可以使用userModel.userInformation ex: (userModel.email)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM