如何在Flutter中存储登录信息?实现登录后自动跳转首页
Hey there! I’ve built this exact flow multiple times for Flutter apps, so let me walk you through a straightforward, reliable implementation:
1. 依赖准备:用SharedPreferences存登录状态
First off, you’ll want a lightweight local storage solution for persisting login state—shared_preferences is perfect for this since it’s easy to use and great for small pieces of data like auth tokens or a simple "logged in" flag. Add it to your pubspec.yaml:
dependencies: flutter: sdk: flutter shared_preferences: ^2.2.2 # Grab the latest version from pub.dev
Run flutter pub get to install the package.
2. 封装登录状态管理服务
Create a simple service class to handle saving/retrieving login info—this keeps your code clean and reusable across the app:
import 'package:shared_preferences/shared_preferences.dart'; class AuthService { // Save login state (extend this to store tokens, user IDs, etc.) static Future<void> saveLoginStatus(bool isLoggedIn, {String? userId}) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool('is_logged_in', isLoggedIn); if (userId != null) { await prefs.setString('user_id', userId); } } // Check current login status static Future<bool> getLoginStatus() async { final prefs = await SharedPreferences.getInstance(); return prefs.getBool('is_logged_in') ?? false; // Default to not logged in } // Clear login info (for logout) static Future<void> clearLoginInfo() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove('is_logged_in'); await prefs.remove('user_id'); } }
3. 启动时判断跳转页面
In your main.dart, use a FutureBuilder to check the login state before rendering the initial page—this ensures we wait for the storage read to finish so we don’t show the wrong page:
import 'package:flutter/material.dart'; import 'auth_service.dart'; import 'login_page.dart'; import 'home_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Auth Flow', theme: ThemeData(primarySwatch: Colors.blue), home: FutureBuilder<bool>( future: AuthService.getLoginStatus(), builder: (context, snapshot) { // Show loading spinner while checking state if (snapshot.connectionState == ConnectionState.waiting) { return const Scaffold(body: Center(child: CircularProgressIndicator())); } // Navigate to home if logged in, else login page return snapshot.data == true ? const HomePage() : const LoginPage(); }, ), ); } }
4. 登录页实现
Create a basic LoginPage—when the user successfully logs in, save their state and navigate to the home page (use pushReplacement to remove the login page from the navigation stack):
import 'package:flutter/material.dart'; import 'auth_service.dart'; import 'home_page.dart'; class LoginPage extends StatelessWidget { const LoginPage({super.key}); void _handleLogin(BuildContext context) async { // Replace this with your actual login logic (API call to validate credentials) bool loginSuccess = true; // Simulate successful login String? userId = 'user_123'; // Simulate user ID from API response if (loginSuccess) { await AuthService.saveLoginStatus(true, userId: userId); // Navigate to home and prevent going back to login Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => const HomePage()), ); } else { // Show error message if login fails ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('登录失败,请检查账号密码')), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('登录页')), body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextField(decoration: const InputDecoration(hintText: '账号')), const SizedBox(height: 10), TextField(decoration: const InputDecoration(hintText: '密码'), obscureText: true), const SizedBox(height: 20), ElevatedButton( onPressed: () => _handleLogin(context), child: const Text('登录'), ), ], ), ), ), ); } }
5. 首页实现(含退出登录)
Add a logout button to the HomePage that clears the login state and navigates back to the login page:
import 'package:flutter/material.dart'; import 'auth_service.dart'; import 'login_page.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); void _handleLogout(BuildContext context) async { await AuthService.clearLoginInfo(); // Navigate back to login and remove home from stack Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => const LoginPage()), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('首页'), actions: [ IconButton( icon: const Icon(Icons.logout), onPressed: () => _handleLogout(context), tooltip: '退出登录', ), ], ), body: const Center(child: Text('欢迎回来!')), ); } }
关键 Tips
- State Persistence:
shared_preferencesstores data locally on the device, so the login state stays even after the app restarts. - Navigation Safety: Using
pushReplacementensures users can’t accidentally navigate back to the login page once they’re logged in. - Async Handling: The
FutureBuilderprevents the app from showing a flash of the wrong page while it checks the login state.
内容的提问来源于stack exchange,提问作者AP aul

