Home > database >  How to disable user to go back to login screen after user login
How to disable user to go back to login screen after user login

Time:08-17

I have an issue that when the user clicks on the login button it redirects to the home page but when I press back it redirects me to the login page again. this is not the correct flow. after the user login, it can't be able to access the login page thats the flow. but in my code, it doesn't work.

Please see my code to help me how to resolve it. How do I disable the login screen after login?

Here is the code:-

Future<void> main() async{

Auth.prefs = await SharedPreferences.getInstance();

runApp(
  Auth.prefs?.getBool("loggedIn") == true ? CardApp() : Login()
);
}

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

@override
_Login createState() => _Login();
}

class _Login extends State<Login>{

var logstatus = Auth.prefs!.getBool('loggedIn');

TextEditingController _user = TextEditingController();
TextEditingController _pass = TextEditingController();

var user = "";
var pass = "";
var statusStep = "";
var Steps = "";
var _UserID = "";
bool _isPass = true;

get import => null;


@override
Widget build(BuildContext context){
final Size size = MediaQuery.of(context).size;
final ThemeData themeData = Theme.of(context);
final double padding = 25;
final sidePadding = EdgeInsets.symmetric(horizontal: padding);
//return SafeArea(
return Scaffold(
    body: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topRight,
            end: Alignment.bottomLeft,
          //colors: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
            colors: const [Colors.white, Colors.white]
        ),
      ),
        width: size.width,
        //height: size.height,
        child: ListView(
          physics: BouncingScrollPhysics(),
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                addVerticalSpace(padding),
                Padding(
                  padding: sidePadding,
                  child: Column(
                    children: <Widget>[
                      addVerticalSpace(20),
                      Image.asset(
                          'assets/images/logo.png',
                        height: 150,
                        scale: 2.5,
                      ), // Image.asset
                    ], //<Widget>[]
                  ),
                ),
                addVerticalSpace(10),
                addVerticalSpace(padding),
                Padding(
                  padding: sidePadding,
                    child: Text(
                        'Sign In',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                        color: Colors.black,
                      ),
                    ),
                ),
                addVerticalSpace(30),
                Padding(
                  padding: sidePadding,
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Expanded(child: TextField(
                            controller: _user,
                            keyboardType: TextInputType.text,
                            obscureText: false,
                            decoration: InputDecoration(
                              enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: Color.fromARGB(153, 154, 154, 154)),
                                  borderRadius: BorderRadius.circular(8.0),
                              ),
                              hintText: 'Email',
                              hintStyle: TextStyle(color: Color.fromARGB(
                                  153, 154, 154, 154)),
                              contentPadding: EdgeInsets.fromLTRB(25,10,25,10),
                                focusedBorder:OutlineInputBorder(
                                  borderSide: const BorderSide(color: Color(0xff9A9A9A99), width: 1.0),
                                  borderRadius: BorderRadius.circular(8.0),
                                )
                            ),
                          ))
                        ],
                      ),
                      addVerticalSpace(15),
                      Row(
                        children: <Widget>[
                          Expanded(child: TextField(
                            controller: _pass,
                            keyboardType: TextInputType.text,
                            obscureText: _isPass,
                            decoration: InputDecoration(
                                suffixIcon: IconButton(
                                    icon: Icon(
                                        _isPass ? Icons.visibility : Icons.visibility_off),
                                    onPressed: () {
                                      setState(() {
                                        _isPass = !_isPass;
                                      });
                                    }),
                              enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: Color.fromARGB(153, 154, 154, 154)),
                                  borderRadius: BorderRadius.circular(8.0),
                              ),
                              hintText: 'Password',
                              hintStyle: TextStyle(color: Color.fromARGB(
                                  153, 154, 154, 154)),
                              contentPadding: EdgeInsets.fromLTRB(25,0,25,0),
                                fillColor: Colors.white,
                                focusedBorder:OutlineInputBorder(
                                  borderSide: const BorderSide(color: Color(0xff9A9A9A99), width: 1.0),
                                  borderRadius: BorderRadius.circular(8.0),
                                )
                            ),
                            style: TextStyle(
                              height: 1.0,
                            ),
                          )
                          )
                        ],
                      ),
                      addVerticalSpace(10),
                            Align(
                              alignment: Alignment.centerRight,
                              child: TextButton(
                                onPressed: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(builder: (context) => Forgotpass()),
                                  );
                                },
                                child: Text(
                                  "Forgot Your Password?",
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 15,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              )
                            ),
                      addVerticalSpace(20),
                      Padding(
                        padding: const EdgeInsets.all(0.0),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            //primary: Color.fromRGBO(152,165,244,1),
                            primary: Color(0xffFDA766),
                            minimumSize: const Size.fromHeight(50),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0),)// NEW
                          ),
                          child: const Text(
                              'SIGN IN'
                          ),
                          onPressed: () async{
                            user = _user.text;
                            pass = _pass.text;

                            final body = null;
                            final url = Uri.https('www.*******.net', '/index.php',{'act':'login','user': user, 'pass': pass});
                            final response = await http.post(
                                url,
                                headers: {'Content-Type': 'application/json'},
                                body: body
                            );
                            int statusCode = response.statusCode;
                            Map<String, dynamic> responseBody = jsonDecode(response.body);
                            setState(() {});

                            var list = responseBody['error'];
                            var stringList = list.join("\n");

                            var statusRes = responseBody['status'];
                            var UserID = responseBody['usr'];
                            if(statusRes == 'success'){

                             
                                Auth.prefs?.setBool("loggedIn", true);
                                Auth.prefs?.setBool("onlinestatus", true);
                                Auth.prefs?.setString('usrid', UserID);
                                FCMService().getFCMToken();

                                Navigator.of(context).pop();
                                Navigator
                                    .of(context)
                                    .pushReplacement(
                                    MaterialPageRoute(
                                        builder: (BuildContext context) => CardApp()
                                    )
                                );
                                  // Navigator.push(
                                  //   context,
                                  //   MaterialPageRoute(
                                  //      builder: (context) => CardApp()),
                                  // );
                             

                            } else {
                              //print('error: ' statusRes);
                              showDialog<String>(
                                context: context,
                                builder: (BuildContext context) => AlertDialog(
                                  title: Text("Login Failed!", style: TextStyle(color: Color(0xff8f9df2), fontWeight: FontWeight.bold),),
                                  content: Text(
                                    '${stringList}',
                                    style: TextStyle(
                                      color: Colors.red,
                                    ),
                                  ),
                                  actions: <Widget>[
                                    TextButton(
                                      //onPressed: () => Navigator.pop(context, 'OK'),
                                      onPressed: () {
                                        Navigator.pop(context, 'OK');
                                      },
                                      child: const Text('OK'),
                                    ),
                                  ],
                                ),
                              );
                            }

                            setState(() {});
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        )
    ),
  );
//);
  }

  }

Here is my login screen see this code and help me with how can i do this.

CodePudding user response:

Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (BuildContext context) => CardApp()));

to this

Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (context) => const CardApp()),
          (Route<dynamic> route) => false);

route dynamic false will remove all route and user cant go back

CodePudding user response:

you are using

Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => CardApp()));

which stack the new screen on the top of the login which on pressing back button is shown again if you want to remove the beneath screen from the stack and disable the back button use this function instread

Navigator.of(context)
.pushAndRemoveUntil(MaterialPageRoute(
builder: (BuildContext context) => CardApp()), (route) => false);
  • Related