You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的Firebase PhoneAuth中使用SharedPreferences维持用户登录

实现OTP验证后保持登录状态的方案

步骤1:OTP验证成功后保存登录状态

在你处理OTP验证的onPressed方法中,验证成功后添加存储登录状态的代码:

onPressed: () async {
  try {
    PhoneAuthCredential credential =
        PhoneAuthProvider.credential(
            verificationId: MyPhone.verify, smsCode: code);
    // 完成登录
    await auth.signInWithCredential(credential);

    // 保存登录状态到SharedPreferences
    await sharedPreferences.setBool('isLoggedIn', true);

    Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(
          builder: (context) => const WelcomeScreen(),
        ),
        (route) => false);
  } catch (e) {
    print("wrong OTP");
  }
},

步骤2:启动App时自动判断登录状态

修改MyApp的home属性,根据SharedPreferences中的状态决定初始页面:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 从全局sharedPreferences获取登录状态,默认未登录
    bool isLoggedIn = sharedPreferences.getBool('isLoggedIn') ?? false;

    return MaterialApp(
      title: 'Therapist App',
      debugShowCheckedModeBanner: false,
      routes: {
        'phone': (context) => MyPhone(),
        'verify': (context) => MyVerify(),
        'home_screen': (context) => HomeScreen()
      },
      // 根据登录状态跳转对应页面
      home: isLoggedIn ? const HomeScreen() : const MyPhone(),
    );
  }
}

额外:添加退出登录功能(可选)

如果需要退出登录,只需清除SharedPreferences中的状态并跳转回登录页:

// 退出登录按钮的点击事件
onPressed: () async {
  await auth.signOut();
  await sharedPreferences.setBool('isLoggedIn', false);
  Navigator.pushAndRemoveUntil(
    context,
    MaterialPageRoute(builder: (context) => const MyPhone()),
    (route) => false,
  );
},

修改完成后,用户完成OTP验证登录后,下次启动App会直接进入主页,无需重复验证。

内容的提问来源于stack exchange,提问作者Newbie Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:15:27