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

Flutter中调用TempClass的onReady方法实现页面跳转失败求助

问题原因

你直接实例化TempClass()的方式不会让GetX框架接管控制器的生命周期,所以onInit和onReady这两个生命周期方法根本不会被触发。GetX的控制器只有通过Get.put()、Get.lazyPut()或者绑定类注册后,框架才会调用它的生命周期钩子。

解决方案

方案1:通过Get.put()注册控制器并触发跳转

修改main函数和MyApp,让控制器被GetX管理,同时确保页面跳转逻辑正常执行:

void main() async {
  final WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await GetStorage.init();
  // 注册控制器,GetX会自动调用onInit和onReady
  Get.put(TempClass());
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      // 初始页面设为过渡页,控制器的onReady会自动跳转
      home: const Scaffold(backgroundColor: Colors.green, body: Center(child: Text('Hello'))),
    );
  }
}

方案2:直接在main函数中处理页面跳转(无需依赖控制器生命周期)

如果不需要控制器的其他业务逻辑,也可以直接在启动阶段读取存储值,确定初始页面:

void main() async {
  final WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await GetStorage.init();
  
  final storage = GetStorage();
  Widget initialScreen;
  if (storage.read('FirstTime') == null) {
    initialScreen = const OnBoardingScreen();
  } else {
    initialScreen = const HomeScreen();
  }

  runApp(MyApp(initialScreen: initialScreen));
}

class MyApp extends StatelessWidget {
  final Widget initialScreen;
  const MyApp({Key? key, required this.initialScreen}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      home: initialScreen,
    );
  }
}
关键补充

如果用方案1的跳转逻辑,建议把Get.to()改成Get.offAll(),这样初始过渡页会被完全替换,避免返回键回到过渡页:

void screenRedirect() {
  if (storage.read('FirstTime') == null) {
    print('I am here in true');
    Get.offAll(() => const OnBoardingScreen());
  } else {
    print('I am here in else part');
    Get.offAll(() => const HomeScreen());
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:43:13