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

Flutter中如何避免闪屏结束后显示CircularProgressIndicator

解决FutureBuilder中CircularProgressIndicator闪屏后显示的问题

问题根源

你的FutureBuilder在AuthService.firebase().initialize()完成前,会默认返回CircularProgressIndicator,而闪屏结束后初始化可能还没完成,导致出现这个不必要的加载圈。

方案一:提前完成初始化(推荐)

将Firebase初始化移到main函数中,在启动App前完成初始化,这样HomePage可以直接判断用户状态,无需FutureBuilder:

修改main函数:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 先完成Firebase初始化
  await AuthService.firebase().initialize();
  runApp(
    MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.grey[300],
      ),
      home: const HomePage(),
      routes: {
        loginRoute: (context) => const LoginView(),
        registerRoute: (context) => const RegisterView(),
        passwordsRoute: (context) => const PasswordsView(),
        verifyEmailRoute: (context) => const VerifyEmailView(),
        createOrUpdatePasswordRoute: (context) => const CreateUpdatePasswordView(),
        passwordGeneratorRoute : (context) => const PasswordGeneratorView(),
        settingsRoute : (context) => const SettingsView(),
      },
    ),
  );
}

修改HomePage组件:

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

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.transparent,
    ));

    final user = AuthService.firebase().currentUser;
    if (user != null) {
      if (user.isEmailVerified) {
        return const PasswordsView();
      } else {
        return const VerifyEmailView();
      }
    } else {
      return const LoginView();
    }
  }
}

方案二:替换默认加载组件

如果不想提前初始化,可以在FutureBuilder的default分支返回与闪屏一致的内容(比如空容器或闪屏Widget),避免突兀的加载圈:

return FutureBuilder(
  future: AuthService.firebase().initialize(),
  builder: (context, snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.done:
        final user = AuthService.firebase().currentUser;
        if (user != null) {
          if (user.isEmailVerified) {
            return const PasswordsView();
          } else {
            return const VerifyEmailView();
          }
        } else {
          return const LoginView();
        }
      default:
        // 返回与闪屏背景一致的容器,或直接复用闪屏组件
        return Container(color: Colors.white);
    }
  },
);

说明

  • 方案一的优势是彻底消除中间加载状态,App启动后直接进入目标页面,适合初始化耗时较短的场景。
  • 方案二适合需要保留FutureBuilder的场景,通过视觉一致性避免用户感知到不必要的加载过程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:45:36