dart 在flutter校友门户应用程序的身份验证过程中,如何根据用户是学生还是校友来不同地路由页面

w8f9ii69  于 2023-03-15  发布在  Flutter
关注(0)|答案(1)|浏览(102)

我最近开始学习应用程序开发使用flutter和目前正在工作的Flutter校友连接门户网站,这将有助于弥合差距的校友和学生之间的某个组织。我想这样的方式来构建我的应用程序,在注册过程中,用户将被询问他是学生还是校友,并且基于所选择的结果,他/她将被引导到不同的页面,并有不同的功能访问的应用程序。我正在使用firebase作为我的后端认证管理器。请帮助我存储和检索用户的信息在认证-即他是校友还是学生,并在应用程序的其余页面中使用这些数据。
我已经创建了下面的注册页面,并将其连接到firebase认证服务。但我想在这里添加一个单选按钮,询问用户他是学生还是校友。请帮助我的代码相同。

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

  @override
  State<SignUpScreen> createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State<SignUpScreen> {
  TextEditingController _emailTextController=TextEditingController();
  TextEditingController _passwordTextController=TextEditingController();
  TextEditingController _usernameTextController=TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: const Text("Sign Up",style: TextStyle(fontSize: 24,fontWeight: FontWeight.bold),),
      ),
      body: Container(
        width: MediaQuery
            .of(context)
            .size
            .width,
        height: MediaQuery
            .of(context)
            .size
            .height,
        decoration: BoxDecoration(
            gradient: LinearGradient(colors: [

              hexStringToColor("6158ce"),
              hexStringToColor("4f33c8"),
              hexStringToColor("eaebff"),
            ], begin: Alignment.center, end: Alignment.bottomCenter)),
        child: SingleChildScrollView(
          child: Padding(
          padding: EdgeInsets.fromLTRB(20, 120, 20, 0),
          child: Column(
            children: <Widget>[
              const SizedBox(
                height: 20,
              ),
              reusableTextField("Enter UserName", Icons.person_outline, false,
                  _usernameTextController),
              const SizedBox(
                height: 20,
              ),
              reusableTextField("Enter Email", Icons.person_outline, false,
                  _emailTextController),
              const SizedBox(
                height: 20,
              ),
              reusableTextField("Enter Password", Icons.person_outline, true,
                  _passwordTextController),
              const SizedBox(
                height: 20,
              ),

              SigninSignupButtons(context, false, (){
                FirebaseAuth.instance.createUserWithEmailAndPassword(email: _emailTextController.text,
                    password: _passwordTextController.text).then((value) {
                      print("created new account!");
                Navigator.push(context, MaterialPageRoute(builder: (context) =>HomeScreen()));
                }).onError((error, stackTrace) {
                  print("Error ${error.toString()}");
                });

              })
            ],
          )),
        ),
      ),
    );

  }
}

以下是我正在使用的可重用小部件-

TextField reusableTextField(String text, IconData icon,bool isPasswordType,TextEditingController controller){
  return TextField(
    controller: controller,
    obscureText: isPasswordType,
    enableSuggestions: !isPasswordType,
    autocorrect: !isPasswordType,
    cursorColor: Colors.white,
    style: TextStyle(color: Colors.white.withOpacity(0.9)),
    decoration: InputDecoration(
      prefixIcon: Icon(
        icon,
        color: Colors.white70,
      ),
      labelText: text,
      labelStyle: TextStyle(color: Colors.white.withOpacity(0.9)),
      filled: true,
      floatingLabelBehavior: FloatingLabelBehavior.never,
      fillColor: Colors.white.withOpacity(0.3),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(30),
        borderSide: const BorderSide(width: 0,style: BorderStyle.none),
      ),

    ),
    keyboardType: isPasswordType
        ? TextInputType.visiblePassword
        : TextInputType.emailAddress,
  );
}

Container SigninSignupButtons(BuildContext context,bool isLogin,Function onTap){
  return Container(
    width: MediaQuery.of(context).size.width,
    height: 50,
    margin: const EdgeInsets.fromLTRB(0, 10, 0, 20),
    decoration: BoxDecoration(borderRadius: BorderRadius.circular(90)),
    child: ElevatedButton(
      onPressed: () {
        onTap();
      },
      child: Text(
        isLogin? 'LOG IN':'SIGN UP',
        style: const TextStyle(
          color: Colors.black87,fontWeight: FontWeight.bold,fontSize: 16),
      ),
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.resolveWith((states){
          if(states.contains(MaterialState.pressed)){
            return Colors.black26;
          }
          return Colors.white;
        }),
        shape:MaterialStateProperty.all<RoundedRectangleBorder>(
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)))),
    ),
  );
}

我想存储和访问用户数据的方式,一旦他/她已经登录作为校友或学生,数据将提供给每个人在应用程序中,所以我可以相应地结构页面和各种用户的功能.
如果你能帮助我解决困扰我好几天的问题,我将非常感激:)

bpsygsoo

bpsygsoo1#

一种解决方案是使用shared_preferences包。
你可以创建一个文件session_manager.dart如下:

import 'package:shared_preferences/shared_preferences.dart';

class SessionManager {
  final String uid = "auth_token";
  final String type = "";
  late SharedPreferences prefs;

  // Set uid
  Future<void> setUid(String uid) async {
    prefs = await SharedPreferences.getInstance();
    prefs.setString(this.uid, uid);
  }

  // Set type
  Future<void> setType(String type) async {
    prefs = await SharedPreferences.getInstance();
    prefs.setString(this.type typpe);
  }

  // Get values
  Future<String?> getUid() async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    String? uid;
    uid = pref.getString(this.uid);
    return uid;
  }

  // Clear values
  clearAll() async {
    prefs = await SharedPreferences.getInstance();
    await prefs.clear();
  }
}

然后您可以在其他地方使用。例如,当您登录时,您可以

SessionManager prefs = SessionManager();

final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
  email: _emailTextController.text,
  password: _passwordTextController.text,
);

String uid = credential.user!.uid;

prefs.setUid(uid);

添加RadioButton后,可以使用作为RadioButton值的type执行prefs.setType(type)
保存会话信息后,您可以使用会话管理器在任何需要的位置访问该信息。下面是一个示例,但有许多实现方法:

class HomePage extends StatefulWidget {
  const HomePage ({super.key});

  @override
  State<HomePage > createState() => _HomeState();
}

class _HomeState extends State<HomePage> {
  late final SessionManager _prefs;

  @override
  void initState() {
    _prefs = SessionManager();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: _prefs.getUid(),
      builder: ((context, snapshot) {
        String uid = snapshot.data ?? "";
        return Scaffold(
          appBar: AppBar(title: Text(uid)),
          body: ...
        );
      }),
    );
  }
}

您也可以阅读更多关于它的内容here

相关问题