skip to Main Content

When I click button
The value is the return value of the Navigator.push() – method.
"because pressing the Button which returns null, does not make the Future go null, but its content. This leads to the unintentional behaviour"

enter image description here
home Screen

PopupMenuButton(
            icon: Icon(Icons.more_vert,color: Colors.black,),
            offset: Offset(0, 40),
            itemBuilder: (context) => [
              PopupMenuItem(
                child: Text('View Cart'),
                onTap: () async {
                final result = await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => CartScreen(cart: cart)),
                  ) ;
                  if(result)
                  {
                    setState(() {
                      
                    });
                  }
                },
              ),

CartScreen

 WillPopScope(

      onWillPop: () {
        Navigator.pop(context,true);

         return new Future(() => false);;
      },
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          iconTheme: IconThemeData(color: Colors.black),
          elevation: 0,
        ),

when i click the button to navigate page

2

Answers


  1. I have like this for example :

    Main Page

      await Navigator.of(context).pushNamed(
            PageNames.routeTest,
          ).then(
            (result) {
                if (result != null && result as bool) {
                    [...do something...]
                }
              }
            },
          );
    

    Test Page

    Could be just a

    /// Could be just like :
    Navigator.of(context).pop(true);
    
    /// Or
     onWillPop: () {
        Navigator.of(context).pop(true);
        return true;
     },
    

    Try to use .then in the future function and use Navigator.of(context).pop. Tell me if that works

    Login or Signup to reply.
  2. Flutter doesn’t recognize the type of result, and casts it as dynamic. In order to avoid this, I suggest you to change the following:

    final result = await Navigator.push(
                        context,
                        MaterialPageRoute<bool>(
                            builder: (context) => CartScreen(cart: cart)),
                      ) ;
                   if(result == null) return ...;
                   if(result)
                      {
                        setState(() {
                          ...
                        });
    
    

    in particular specify explicitly the return type of MaterialPageRoute and implement something when return is null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search