How to return Future or any other types from a function in dart

Import "dart:async" package, and add async keyword to your method signature like

Future<bool> _onWillPop() async{

After this, you will just need to return a boolean value whenever your method completes its processing just like any other function


I had exactly the same problem.

I solved it by returning Future.value(false); If the value is true I get the black screen.

Future<bool> _onBackPressed() {
 if (!widget.editing) {
   Navigator.pop(context, true);
   return Future.value(false);
 } else {
   return showDialog(...

Your comment: I need to display an alert on pressing the back button. If the user made any changes to the data, the changed will become true and at that time only I need to display the alert.

You don't have to check for that.

You can refer below example(from official material examples, here you can see a complete example) and get some idea:

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

bool _formWasEdited = false;

final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

Future<bool> _warnUserAboutInvalidData() async {
    final FormState form = _formKey.currentState;
    if (form == null || !_formWasEdited || form.validate())
      return true;

    return await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: const Text('This form has errors'),
          content: const Text('Really leave this form?'),
          actions: <Widget> [
            new FlatButton(
              child: const Text('YES'),
              onPressed: () { Navigator.of(context).pop(true); },
            ),
            new FlatButton(
              child: const Text('NO'),
              onPressed: () { Navigator.of(context).pop(false); },
            ),
          ],
        );
      },
    ) ?? false;
  }

And in the Form widget:

child: new Form(
    key: _formKey,
    autovalidate: _autovalidate,
    onWillPop: _warnUserAboutInvalidData,
    //........

Tags:

Dart

Flutter