You need to enable JavaScript to run this app. Flutter实现API请求成功后自动关闭启动页Splash Screen
优惠活动
大模型
产品
解决方案
定价
更多

Flutter实现API请求成功后自动关闭启动页Splash Screen

核心问题根源

当前实现存在两处时序断层,完全无法满足按业务流程触发跳转的需求:

  • AnimatedSplashScreen内置的固定时长跳转逻辑,和initState中触发的API请求、本地存储流程是完全并行执行的,没有任何时序联动。1000ms的计时结束触发跳转时,API请求大概率还没返回,更等不到所有本地写入操作完成。
  • 原代码没有异常捕获逻辑,一旦网络请求失败、JSON解析报错,整个流程会永久阻塞,启动页卡死无法跳转。
具体改造方案
  • 切断AnimatedSplashScreen的短时长自动跳转绑定:移除自动关联的nextScreen参数,把duration设置为30秒的兜底超时阈值,仅作为网络完全不可用时的防卡死兜底,不承载正常流程的跳转逻辑。
  • 封装统一的跳转方法,加入防重复触发的状态标记,等所有API请求返回、本地安全存储的写入操作全部await完成后,手动触发页面跳转。
  • 补全全流程的异常捕获,不管接口请求、数据解析、本地存储哪一步出错,都能正常跳转到欢迎页,不会出现启动页卡死的情况。
  • 修正原代码中的拼写bug:原存储key_TaxPercentTaxPercent存在重复文本,会导致后续读取税率值时找不到对应数据,需改为正确的_TaxPercent。
改造后的完整实现代码
class _SplashPageState extends State<SplashPage> {
  // 防重复跳转标记
  bool _hasNavigated = false;

  @override
  void initState() {
    super.initState();
    _initAppStartupData();
  }

  Future<void> _initAppStartupData() async {
    // 30秒兜底超时,防止接口挂死导致永久卡启动页
    Future.delayed(const Duration(seconds: 30), () {
      if (!_hasNavigated) _navigateToWelcome();
    });

    try {
      final res = await http.get(
        Uri.parse('http://retailapi.airtechsolutions.pk/api/settings/user/2170'),
      );
      final Map<String, dynamic> responseMap = json.decode(res.body);

      if (int.parse(responseMap['Status'].toString()) == 1) {
        final storage = const FlutterSecureStorage();
        // 等待所有本地存储写入完成
        await storage.write(
          key: '_LocationID',
          value: responseMap['LocationID'].toString(),
        );
        await storage.write(
          key: '_UserID',
          value: responseMap['UserID'].toString(),
        );
        await storage.write(
          key: '_TaxPercent',
          value: responseMap['TaxPercent'].toString(),
        );
        await storage.write(
          key: '_DeliveryCharges',
          value: responseMap['DeliveryCharges'].toString(),
        );
        await storage.write(
          key: '_Currency',
          value: responseMap['Currency'].toString(),
        );
      }
      // 全流程执行完成后触发跳转
      _navigateToWelcome();
    } catch (e) {
      // 捕获所有流程异常,异常场景下也正常跳转
      debugPrint('启动页数据初始化异常: $e');
      _navigateToWelcome();
    }
  }

  void _navigateToWelcome() {
    if (_hasNavigated) return;
    _hasNavigated = true;
    Navigator.pushReplacement(
      context,
      PageTransition(
        type: PageTransitionType.fade,
        child: const SplashWelcomePage(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedSplashScreen(
      backgroundColor: kPrimaryColor,
      splash: 'assets/icons/logo.png',
      splashTransition: SplashTransition.fadeTransition,
      duration: 30000,
      animationDuration: const Duration(milliseconds: 1500),
    );
  }
}
落地注意事项
  • 必须保留跳转状态标记:防止正常流程跳转和30秒兜底超时同时触发,导致重复压栈、页面栈报错。
  • 所有storage.write操作必须显式加await,等数据完全写入磁盘后再跳转,避免欢迎页读取本地存储时出现空值。
  • 网络请求地址要用Uri.parse包裹,不能直接传字符串,适配新版http包的接口参数要求。
  • 全流程用try-catch块包裹,不管是网络异常、JSON解析失败、存储写入报错,都能保证流程闭环,不会出现启动页无响应的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 13:45:03