用户退出后仍处于登录状态

时间:2021-01-17 08:57:10

标签: flutter authentication sharedpreferences

我正在使用 flutter 制作一个应用程序,我使用了 shared_preferences 包,在身份验证阶段我面临一个问题,当我构建应用程序时,用户登录,当我注销并在杀死它后重新启动应用程序时,它仍然进入主页, 这是我的代码

main.dart

bool checkingKey;


Future<bool> checkKey() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool checkingKey=prefs.containsKey("jwt");
  print("$checkingKey");
  return checkingKey;
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Paint.enableDithering = true;
  await checkKey().then((value){
    checkingKey=value;
  });
  runApp(MyApp());
}


class MyApp extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    // bool check=checkKey().then((bool value) => true);
    print("hello=$checkingKey");
    return MaterialApp(
        home: AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle(
            statusBarColor: Colors.transparent,
          ),
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            body: Container(
              color: Color(0xffccffcc),
              child:checkingKey==false?LoginPage():mainPage()
            ),
          ),
        ),
        routes: <String,WidgetBuilder>{
          '/home':(BuildContext context)=>mainPage(),
          '/login':(BuildContext context)=>LoginPage(),
      }
      );
  }
}

login_signup_Auth.dart

Future<void> attemptLogIn(String username, String password,BuildContext context) async {
                                                          ///?final storage =parent_inherit.of(context);
                                                          ///?var verify=storage.verify;
  SharedPreferences prefs = await SharedPreferences.getInstance();
  print("$username $password");
  final http.Response res = await http.post(
      "https://green-earth.herokuapp.com/signin",
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
        // 'authorization':'Bearer '+
      },
      body: jsonEncode(<String, String>{
        "email": username,
        "password": password
      }),
  );
  if(res.statusCode == 200) {
    prefs.setString('jwt',res.body);
    var value=prefs.getString('jwt');
    print("storage= ${value.isEmpty}");
    Navigator.of(context).pushNamed('/home');
  }
  else{
    return _showMyDialoglogin(context,res.statusCode);
  }
}


void logoutOutOfApp(BuildContext context) async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.clear();
  Navigator.of(context).pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
}

在没有更改任何内容的第二次构建中,检查关键变量返回“true”,我不知道,这怎么可能!!!!!!

我不明白我做错了什么,如果你看到任何其他可以使程序高效的问题或任何其他应使用的代码。请告诉

非常感谢!!

1 个答案:

答案 0 :(得分:1)

你为什么要把事情复杂化? 您的 main.dart 可以看起来像这样

bool checkingKey;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Paint.enableDithering = true;

  var prefs = await SharedPreferences.getInstance();
  checkingKey = prefs.containsKey("jwt");

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("hello=$checkingKey");
    return MaterialApp(
      home: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
        ),
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Container(
            color: Color(0xffccffcc),
            child: !checkingKey ? LoginPage() : mainPage(),
          ),
        ),
      ),
      routes: <String,WidgetBuilder>{
        '/home':(BuildContext context) => mainPage(),
        '/login':(BuildContext context) => LoginPage(),
      },
    );
  }
}
相关问题