【问题标题】:How to return to onWillPop function nothing? Flutter/Dart如何返回 onWillPop 函数什么都没有?颤振/飞镖
【发布时间】:2021-04-07 13:14:16
【问题描述】:

所以最近我一直在做一个包含测验的小型移动应用项目。我希望我的应用程序做的是询问用户是否想退出测验或留下,但只有当我的问题索引为 0 时(因为我已经让我的用户可以回到问题)。所以我写下了问题布局小部件,并将 WillPopScope 小部件放在 Scaffold 上方,这样我就可以使用他的 onWillPop 属性了。

return BlocProvider(
      create: (context) => CardsCubit(),
      child: ScreenUtilInit(
        designSize: Size(414, 896),
        allowFontScaling: true,
        builder: () => WillPopScope(
          onWillPop: exitFromExamRequest(context) ,
                  child: Scaffold(
            body: ... 

还有我的 exitFromExamRequest 函数:

Future<bool> exitFromExamRequest(BuildContext context) async {
  if (context.read<ExamQuestionIndexCubit>().state == 0) {
    return await showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text(
                'Czy napewno chcesz opuścić test? Twoje odpowiedzi nie zostaną zapisane!',
                style: kTitleTextStyle.copyWith(
                  fontSize: kSpacingUnit.w * 1.8,
                ),
              ),
              actions: [
                TextButton(
                  child: Text('Tak',
                      style: TextStyle(
                          color: Theme.of(context).textTheme.bodyText1!.color)),
                  onPressed: () => Navigator.pop(context, true),
                ),
                TextButton(
                  child: Text('Nie',
                      style: TextStyle(
                          color: Theme.of(context).textTheme.bodyText1!.color)),
                  onPressed: () => Navigator.pop(context, false),
                ),
              ],
            ));
  }

  // return await Future.value(false); Doesn't work
  // return await Future(() => false); Doesn't work either
}

我使用 await Future.value(false)await Future(() => false) 的方式不起作用,并且出现错误提示:

The argument type 'Future<bool>' can't be assigned to the parameter type 'Future<bool> Function()?'.

这个问题有什么解决办法吗??我会很高兴为您提供一个方法:)

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    return false; 怎么样?应该可以的。

    事实上,你的问题并不在你想的地方。

    在可读性方面,我会先采用较短的变体。然后,您需要返回 bool,而不是 T?,showDialog 返回:

    if (context.read<ExamQuestionIndexCubit>().state != 0) {
        return false;
    }
    
    final result = await showDialog<bool>(...
    
    if(result == null) {
        // I don't know what you want here... probably false:
        return false;
    }
    
    return result;
    

    【讨论】:

    • 好的,问题是 onWillPop 属性不需要函数,而只需要函数的名称。所以我改变了我的函数,它不需要参数并将它放入小部件类中。
    猜你喜欢
    • 2019-11-22
    • 2019-02-05
    • 1970-01-01
    • 2020-11-28
    • 2021-02-27
    • 1970-01-01
    • 2021-11-18
    • 2020-12-25
    • 2020-11-05
    相关资源
    最近更新 更多