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

Flutter空安全下WillPopScope的onWillPop参数类型不匹配如何解决

问题原因

空安全升级后,WillPopScope组件的onWillPop参数要求接收返回值为Future<bool>类型的函数,而showDialog方法的返回值天生为可空的Future<T?>(比如用户点击系统返回键关闭弹窗时会返回null),原代码中showExitPopUp方法返回Future<bool?>,和要求的类型不匹配,因此触发类型报错。

修复方案

需要调整showExitPopUp方法的返回值类型为Future<bool>,同时对showDialog的返回值做非空兜底处理,空值时默认返回false(代表不退出页面),同时补全参数类型符合空安全规范即可。
修复后完整代码如下:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ExitPopUp extends StatelessWidget {
  // 补全page参数的类型,空安全下不允许隐式dynamic类型
  final Widget page;
  const ExitPopUp(this.page, {super.key});

  @override
  Widget build(BuildContext context) {
    // 返回值改成非空的Future<bool>
    Future<bool> showExitPopUp() async {
      // 对showDialog的返回值做兜底,null的话默认返回false
      final? result = await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(20.0))),
              backgroundColor: const Color.fromRGBO(0, 68, 69, .5),
              title: const Text("Confirm", style: TextStyle(color: Colors.white)),
              content: const Text("Do you want to Exit ?",
                  style: TextStyle(color: Colors.white)),
              actions: <Widget>[
                ElevatedButton(
                    child: Text(
                      "No",
                      style: TextStyle(color: Colors.yellow[100]),
                    ),
                    onPressed: () {
                      Navigator.pop(context, false);
                    }),
                ElevatedButton(
                    child: Text("Yes",
                        style: TextStyle(color: Colors.yellow[100])),
                    onPressed: () {
                      SystemNavigator.pop();
                    })
              ],
            );
          });
      return result ?? false;
    }

    return WillPopScope(child: page, onWillPop: showExitPopUp);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:27:01