0

I have recently started learning App development using flutter and am currently working on a Flutter Alumni connection portal which will help bridge the gap between the alumni and the students of a certain organization. I want to structure my app in such a way that during sign up,The user would be ask whether he is a student or an alumni and based on the selected result he/she would be directed to different pages and have different functionality access of the app. I am using firebase as my backend authentication manager. Please help me store and retrieve the info of the user during authentication-ie whether he is an alumni or a student and use that data in rest of the pages of the app.

I have created the following sign up page and connected it to firebase authentication service. But i want to add a radiobutton here which would ask the user whether he is a student or an alumni.Please help me with the code for the same.

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()}");
                });

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

  }
}

Following are the reusable widgets i am using-

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)))),
    ),
  );
}

I want to store and access the user data in such a way that once he/she has signed in as an alumni or a student that data will be available everyone in the app so i can structure pages and functionalities of various users accordingly.

I will be really grateful if you will help me with the given problem which is troubling me for days now :)

Ilhamm
  • 1
  • 1

1 Answers1

0

One solution is to use the shared_preferences package.

You can create a file session_manager.dart like so:

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();
  }
}

which you can then use elsewhere. For example, when you sign in, you can do

SessionManager prefs = SessionManager();

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

String uid = credential.user!.uid;

prefs.setUid(uid);

Once you add the RadioButton, you can do prefs.setType(type) with the type being the value of the RadioButton.

After you have saved the session information, you can access that information using the session manager wherever you want. Here's an example, though there are many ways of implementing it:

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: ...
        );
      }),
    );
  }
}

You can read more about it here as well.

raw-chicken
  • 351
  • 9