Goldlightdrake
Goldlightdrake

Reputation: 183

How to return to onWillPop function nothing? Flutter/Dart

so latelly I've been working on little mobile app project with quiz inside of it. What I want my app to do is ask user to if he wants to quit quiz or stay, but only when index of my questions are 0 (Because I've made my user can back to questions). So I wrote down the question layout widget and placed above Scaffold the WillPopScope widget, so I can use his onWillPop property.

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

And my exitFromExamRequest function:

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
}

The way I did with await Future.value(false) or await Future(() => false) doesn't work and there is a error which says:

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

Any solutions to this problem?? I'll be greatful for even showing a way :)

Upvotes: 1

Views: 1583

Answers (1)

nvoigt
nvoigt

Reputation: 77304

How about return false;? That should work.

Matter of fact, your problem is not where you think it is.

In terms of readability, I would take the shorter variant first. Then, you need to return a bool, not a T? the showDialog returns:

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;

Upvotes: 1

Related Questions