颤抖:我无法保持用户登录

时间:2020-02-14 12:26:56

标签: flutter dart sharedpreferences

我想在用户首次登录后保持用户登录,但是每次我从手机后台关闭该应用程序时,用户都将注销,并且必须从头开始重新登录

这是我登录的api方法

Future<dynamic> login(String email, String password ) async {
    final Map<String, dynamic> body = {'email': email, 'password': password  };

    _isLoading = true;
    notifyListeners();

    http.Response response = await http.post(Environment.userLogin,
        body: json.encode(body), headers: Environment.requestHeader);

        SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> res = json.decode(response.body);
    var results;
    if (res['code'] == 200) {

      _user = User.fromJson(res['message']);

      prefs.setString('email', _user.email);
      results = true;
    } else {

      results =
          FailedRequest(code: 400, message: res['error'], status: false);
    }

    _isLoading = false;
    notifyListeners();
    return results;
  }

这是主要功能

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var email = prefs.getString('email');
  print(email);
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]).then((_) => runApp(new MyApp()));

}

有人可以帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

DartPad上的示例

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FutureBuilder(
        future: SharedPreferences.getInstance(),
        builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
          if (!snapshot.hasData) return Container();

          final isLoggedIn = snapshot.data.getString("email") != null;
          return isLoggedIn ? Home() : Login();
        },
      ),
    );
  }
}