Search code examples
flutterdartdart-null-safety

How to handle null error of WillPopScope widget when press back button?


I use WillPopScope widget into Home Page Screen to prevent app from exiting. When user press back button without confirmation alert dialog

body: WillPopScope(
  onWillPop: () => StaticUI()
      .onScreenPop(Routes.customerProcessScreen, context) as Future<bool>,
  child: SingleChildScrollView(
  ...
),
);
Future<bool>? onScreenPop(String route, BuildContext context) async => await showDialog(
  useSafeArea: true,
  context: context,
  barrierDismissible: true, // user must tap button!
  builder: (BuildContext context) {
    return Stack(
      children: [
           ...
      ],
    );
  },
);

But I get a null error when I press back button to dismiss alert (when closing alert)!


E/flutter ( 4688): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'Null' is not a subtype of type 'FutureOr<bool>'
E/flutter ( 4688): #0      StaticUI.onScreenPop (package:hesabate/Utils/statics.dart:275:74)
E/flutter ( 4688): <asynchronous suspension>
E/flutter ( 4688): #1      ModalRoute.willPop (package:flutter/src/widgets/routes.dart:1357:11)
E/flutter ( 4688): <asynchronous suspension>
E/flutter ( 4688): #2      NavigatorState.maybePop (package:flutter/src/widgets/navigator.dart:4966:45)
E/flutter ( 4688): <asynchronous suspension>
E/flutter ( 4688): 

SDK version

environment:
  sdk: '>=2.12.0 <3.0.0'

Solution

  • I did some edits in my code to check for null returns , so it's working now .

    Future<bool> onScreenPop(String route, BuildContext context) async {
    final result = await showDialog(
      useSafeArea: true,
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return Stack(
          children: [
            ...
          ],
        );
      },
    );
    
       if (result == null) {
         return false;
        } else {
         return result;
        }
    }