Sometimes we may need a modal view in Flutter. We will use PageBuilder to create a custom modal view.

In this simple example, whenever the user presses the button, a modal view will be shown.

...
FlatButton(
  onPressed: () {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (BuildContext context) {
          return new CupertinoPageScaffold(
            child: new Text('Hello World'),
          );
        }
      )
    );
  }
)
...

However, this will overlap all of the view as shown below. But we want to show a “modal like” screen.

Fullscreen modal.

We want to have a modal that will show a little bit of the previous screen behind. There is a solution for that. We will use PageRouteBuilder.

...
FlatButton(
  onPressed: () {
    Navigator.of(context).push(
      // We will now use PageRouteBuilder
      PageRouteBuilder(
        opaque: false,
        pageBuilder: (BuildContext context, __, __) {
          // Create a Scaffold widget here.
        }
      )
    ), // PageRouteBuilder
  }
)
...

We then create a Scaffold widget.

...
FlatButton(
  onPressed: () {
    Navigator.of(context).push(
      // We will now use PageRouteBuilder
      PageRouteBuilder(
        opaque: false,
        pageBuilder: (BuildContext context, __, __) {
          return new Scaffold(
            backgroundColor: Colors.black45,
            body: // Create a container with margins
          ); // Scaffold
        }
      )
    ), // PageRouteBuilder
  }
)
...

Then the body of the Scaffold will contain a Container widget with margins.

...
FlatButton(
  onPressed: () {
    Navigator.of(context).push(
      // We will now use PageRouteBuilder
      PageRouteBuilder(
        opaque: false,
        pageBuilder: (BuildContext context, __, __) {
          return new Scaffold(
            backgroundColor: Colors.black45,
            body: new Container(
              margin: EdgeInsetsDirectional.only(
                          top: 60.0, end: 2.0)
              color: Color.white,
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: new FlatButton(
                 child: Text('Close'),
                 onPressed: () {
                   Navigator.pop(context);
                 }
              ), // FlatButton
            ), // Container
          ); // Scaffold
        }
      )
    ), // PageRouteBuilder
  }
)
...

That’s it. Now we will have a modal view with semi-transparent background.

Leave a Reply

Your email address will not be published. Required fields are marked *