flutternavigationmodal-dialog

How do I pop a view with Cancel in Flutter if a return is expected?


I would like some help using a cancel button to pop the current modal popup, but not return the required data.

Here is the code that requires an EntryData class on return from the modal popup DataEntryView:

Future<void> _addEvent(BuildContext context) async {
// this Navigator.push returns a Future that completes after calling
// Navigator.pop on the DataEntryView.

EntryData result = await Navigator.of(context).push(
  CupertinoPageRoute(
    fullscreenDialog: true,
    builder: (context) {
      return const DataEntryView();
    },
  ),
);

Here is the code for the cancel button in the DataEntryView:

               // Cancel button
                  const SizedBox(height: 30),
                  CupertinoButton(
                    onPressed: () {
                      Navigator.pop(context, newEntry);
                    },
                    child: const Text('Cancel'),
                  ),

In the cancel button I am sending back an EntryData named newEntry with dummy info to test to see if it's real:

 EntryData newEntry = EntryData(2000, "Blank", "Do Not Use");

But is there another way to tell the Future that there is no data and just pop the modal view? Because now I have to write code to test newEntry to see if it's a dummy.

Any help would be appreciated. I'm new to Flutter.


Solution

  • Try changing the result variable from a EntryData to an EntryData? which means "either an EntryData or null".

    EntryData? result = await Navigator.of(context).push(
      CupertinoPageRoute(
        fullscreenDialog: true,
        builder: (context) {
          return const DataEntryView();
        },
      ),
    );
    

    Then if you run Navigator.pop(context) with no second parameter, result will be null, and you can do something different in that case:

    if (result == null) {
      // do something
    }
    

    New cancel button code:

    // Cancel button
    const SizedBox(height: 30),
    CupertinoButton(
      onPressed: () {
        Navigator.pop(context); // pop with no result
      },
      child: const Text('Cancel'),
    ),