使用setState()在应用程序中保持用户登录

时间:2019-07-31 06:16:43

标签: flutter

我正在尝试让我的应用程序用户登录,直到他们注销为止。这是一个访问api进行身份验证的应用。我想让用户使用setState方法而不是令牌身份验证方法登录。我能够成功登录,但是当我关闭并再次打开该应用程序时,我必须重新登录。

以下是使用setState函数具有相关代码的文件。我找不到我的错误。

main.dart:

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {


  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
   return new MaterialApp(
       title: "Splash and Token Authentication",
       routes: <String, WidgetBuilder>{
         "/HomeScreen": (BuildContext context) => HomeScreen(),
         "/LoginScreen": (BuildContext context) => LoginScreen(),

       },
       //state variable is in loginScreen.dart file
       home: ((state == loginState.LOGGED_IN)?        HomeScreen():LoginScreen())
   );
 }
 @override
 void initState() {
   super.initState();
 }
}

loginScreen.dart:

import ...

enum loginState{ LOGGED_IN, LOGGED_OUT}

loginState state;

const URL = "http://www.google.com";

class LoginScreen extends StatefulWidget {
   @override
  State<StatefulWidget> createState() {
    return new LoginScreenState();
  }

}

class LoginScreenState extends State<LoginScreen> {

  final TextEditingController _userNameController =     TextEditingController();
  final TextEditingController _passwordController =   TextEditingController();
  String _welcomeString = "";

  Future launchURL(String url) async {
    if(await canLaunch(url)) {
      await launch(url, forceSafariVC: true, forceWebView: true);
    } else {
      showDialogSingleButton(context, "Unable to reach your     website.", "Currently unable to reach the website $URL. Please try   again at a later time.", "OK");
    }
 }

  @override
  void initState() {
    super.initState();

    _saveCurrentRoute("/LoginScreen");
  }

  _saveCurrentRoute(String lastRoute) async {
    SharedPreferences preferences = await    SharedPreferences.getInstance();
    await preferences.setString('LastScreenRoute', lastRoute);
  }

 }

  @override
  Widget build(BuildContext context) {
     //LoginScreen UI
  }
 }

homeScreen.dart:

import ...

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() =>  _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  @override
  void initState() {
    super.initState();
    _saveLoginState();
    _saveCurrentRoute("/HomeScreen");
  }

  _saveCurrentRoute(String lastRoute) async {
    SharedPreferences preferences = await    SharedPreferences.getInstance();
    await preferences.setString('LastScreenRoute', lastRoute);
  }

  Future<void> _saveLoginState() async{

    setState(() {
      state = loginState.LOGGED_IN;
    });
  }

 @override
  Widget build(BuildContext context) {
   //HomeScreen UI
}

2 个答案:

答案 0 :(得分:0)

在MaterialApp中使用onGenerateRoute 登录后,您可以在此处设置initialRoute,将更改SharedPreferences登录到您的loginScreen路由。然后您可以在应用启动时获取路线。

@override
  Widget build(BuildContext context) {
    String initialRoute = '/';
    return MaterialApp(
      theme: _themeData,
      onGenerateRoute: (s) => _getCurrentRoute(s),
      initialRoute: initialRoute,
    );
  }



_getCurrentRoute(RouteSettings settings) {
    print(settings.arguments);
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(
            builder: (context) => PageRouter(
                  child: LogInPage(),
                  isSearchBar: false,
                ));
      case '/home':
        return MaterialPageRoute(
            builder: (context) => PageRouter(
                  child: Home(),
                  isSearchBar: true,
                ));
      case '/plp_page':
        return MaterialPageRoute(
            builder: (context) => PageRouter(
                  child: PlpPage(),
                  isSearchBar: false,
                ));
      case '/pdp_page':
        return MaterialPageRoute(builder: (context) => PdpPage());
      case '/cart_page':
        return MaterialPageRoute(
            builder: (context) => PageRouter(
                  child: CartPage(),
                  isSearchBar: false,
                ));

    }
  }

答案 1 :(得分:0)

您正在寻找shared_preferences软件包。

用户登录时需要将数据保存到共享首选项中,而用户注销时则需要清除所有共享首选项。

当用户再次打开应用程序时,您需要检查Shared Preference是否具有用户数据。

示例代码:

//Initialise SharedPreferences
SharedPreferences prefs = await SharedPreferences.getInstance();

//set some value in it.
//In your case your user data like some id, email or anything
await prefs.setInt('key', value);

//Getting data from preference.
final someName = prefs.getInt('key')