Getx onInit 未调用

Hoo*_*Hoo 4 splash-screen dart flutter flutter-getx

应用程序卡在启动屏幕上有什么原因吗?我使用getx状态管理。如果 authToken 不为空,则应转到主页。但onInit在控制器类中没有调用。

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/splashScreen',
      getPages: [
        GetPage(name: '/splashScreen', page: () => SplashScreen(),binding: Bind()),
        GetPage(
            name: '/login', page: () => LoginPage(), binding:Bind()),
        GetPage(
            name: '/mainPage', page: () => MainPage(), binding:Bind())
      ],
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        LocalizationDelegate(),
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''),
        const Locale('zh', ''),
      ],
      title: 'Sample',
      theme: ThemeData(
        accentIconTheme: const IconThemeData.fallback().copyWith(
          color: Colors.white,
        ),
        primaryTextTheme: TextTheme(headline6: TextStyle(color: Colors.orange)),
        primarySwatch: white,
        primaryIconTheme: const IconThemeData.fallback().copyWith(
          color: Colors.white,
        ),
      ),
      // home: SplashScreen(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

启动画面

class SplashScreen extends GetView<MainPageController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
          height: double.infinity,
          width: double.infinity,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Column(
                children: <Widget>[
                  Container(
                      height: 250,
                      width: 250,
                      child: Image.asset('assets/xxx.png')),
                  SizedBox(
                    height: 10,
                  ),
                ],
              )
            ],
          )),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

主页控制器

class MainPageController extends GetxController {
  final con = Get.find<ProductDefectsController>();
  final con1 = Get.find<ProductQualityController>();
  final con2 = Get.find<ProductController>();

  var tabIndex = 0;

  @override
  void onInit() async {
    print("call onInit");  // this line not printing
    // checkIsLogin();
    // print("ww");
    super.onInit();
  }
}
Run Code Online (Sandbox Code Playgroud)

绑定

class Bind extends Bindings {
  Repository? _repository;
 
  Bind() {
    final _service = Get.put(Service());
    final _db = Get.put(Db());

    final _dao = Get.put(Dao(_db));
    _repository = Get.put(Repository(_dao, _service));
  }

  @override
  void dependencies() {
    Get.lazyPut<MainPageController>(() => MainPageController());  
    Get.lazyPut<LoginPageController>(
        () => LoginPageController(_repository!));
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我尝试使用middlewares,但出现错误

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/splashScreen',
      getPages: [
        GetPage(
            name: '/splashScreen',
            page: () => SplashScreen(),
            binding: Bind(), middlewares: [GlobalMiddleware()]),
                ...
      ],
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
              ....
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

中间件

  class GlobalMiddleware extends GetMiddleware {
      final authService = Get.find<LoginPageController>();
    
      @override
      RouteSettings? redirect(String? route) {
        print(authService.isLogin.value);
        return authService.isLogin.value == true
            ? RouteSettings(
                name: "/mainPage",
              )
            : RouteSettings(name: "/login");
      }
    }
Run Code Online (Sandbox Code Playgroud)

错误

"LoginPageController" not found. You need to call "Get.put(LoginPageController())" or "Get.lazyPut(()=>LoginPageController())"
Run Code Online (Sandbox Code Playgroud)

S. *_*GIR 7

在使用/查找绑定之前,您需要在某处初始化它们。一个好地方是将绑定类的实例(在您的情况下Bind)提供给initialBinding以下属性GetMaterialApp

GetMaterialApp(
...
initialBinding: Bind(),
...
) 
Run Code Online (Sandbox Code Playgroud)

然后你可以使用中间件方法。但是控制器方法可能还无法工作,因为控制器实例尚未在页面/视图上使用。onInit请记住,仅当从页面/视图使用/调用控制器/依赖项时,控制器(或任何其他依赖项)才会被初始化(从而调用生命周期方法,例如)。这在你的情况下没有发生。