第一种方法
在路由配置的时候应该有二个page配置
'/': (context) => HomePage(),
'/login': (context) => LoginPage(),
main.dart中的初始化配置如下
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
isLogin = await obtionLoginData();//异步获取本地状态 值传到下面方法
runApp(MyApp());
}
MaterialApp(
initialRoute: isLogin ? '/' : '/login'
onGenerateInitialRoutes: (name) {//必须实现 不然会先加载'/'页面才会加载'/login'页面
return [MaterialPageRoute(builder: (context){
return LoginPage();
})]
}
)
第二种方法
void main() async { runApp(MyApp());}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<String> obtionSharedPrefs() async {//异步获取本地数据
SharedPreferences prefs = await SharedPreferences.getInstance();
phone = prefs.getString('phone') ?? '';
return phone;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureBuilder<String>(
future: obtionSharedPrefs(),
builder: (BuildContext context,AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();//加载中
} else if (snapshot.connectionState == ConnectionState.done) {//加载完成
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData && snapshot.data.isNotEmpty) {
return Home();//已经登录过 直接进入首页
} else {
return Login();//没有登录过 进入登录页面
}
} else {//异常
return Text('State: ${snapshot.connectionState}');
}
},
),
);
}
}
第三种方法
使用getx框架中的路由middlewares配置实现
///路由配置
class AppPage {
static final routes = [
GetPage(name: "/", page: ()=> const LoginPage(), middlewares: [AppMiddleware()),
GetPage(name: "/login", page: ()=> const HomePage()]),
];
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await AppTool.initializeApp();;//异步初始化数据 加载sdk
runApp(MyApp());
}
return GetMaterialApp(
initialRoute: "/",
getPages: AppPage.routes,
);
/*登录中间件*/
class AppMiddleware extends GetMiddleware {
@override // 优先级越低越先执行
int? get priority => -1;
@override
RouteSettings? redirect(String? route) {
final accessToken = UserSinglen().accessToken;//获取token 如果token没值就进入登录页面
return accessToken == null ? const RouteSettings(name:'/login') : null;
}
}