Как сделать всплывающее окно flutter

Обновлено: 18.04.2024

Редкое приложение может обойтись одним окном или одной страницей. Во Flutter и то и другое – виджеты. Для переключения между окнами или виджетами нужно использовать Navigator.

Navigator – виджет-класс, позволяющий управлять стеком дочерних виджетов, т.е. открывать, закрывать и переключать окна или страницы. Когда мы используем MaterialApp, то экземпляр класса Navigator уже создан, и его не надо объявлять с помощью слова new.
А можно просто вызывать методы, для управления стеком виджетов:

  • Navigator.push;
  • Navigator.pushNamed;
  • Navigator.pop;
  • и другие.

В этом уроке мы рассмотрим некоторые основные возможности класса Navigator:

1. Открытие нового окна и возврат к предыдущему

Чтобы открыть новое окно, нам нужно добавить в стек маршрутов новый маршрут. Это можно сделать с помощью Navigator.push, с указанием двух обязательных параметров: context и виджета MaterialPageRoute (или PageRouteBuilder).

Чтобы вернуться к предыдущему окну, используем метод Navigator.pop.

Создадим простой пример из двух окон.

В главном окне у нас будет кнопка, при нажатии на которую выполнится код «открытия окна»:

Класс MaterialPageRoute позволяет открыть полноэкранное окно с эффектом присущим для вашей мобильной системы, это простой и удобный способ. Можно воспользоваться другим виджетом PageRouteBuilder, он более сложный по конструкции, мы рассмотрим его в конце этого урока.

Во втором окне будет кнопка возвращения к первому окну с помощью:

Листинг кода примера из двух окон

Минус такого подхода в том, что в большом приложении с большим количеством классов и виджетов, управлять такой структурой будет очень сложно. В каждый файл где вы будет использовать тот или иной виджет «окна» вам придется подключать его через import, и в случае замены на другой производить переименование виджета во всем проекте.

2. Использование маршрутов для навигации – routes

Поэтому чтобы избавиться от вышеуказанных проблем нужно использовать маршруты. Имена маршрутов принято использовать как пути в директориях: '/', '/client', '/client/123', и т.п.

Маршрут главного окна по умолчанию: '/'.

Когда в предыдущем примере в параметре home мы указали виджет MainScreen() – тем самым мы задали маршрут '/'.

Зададим маршруты в виджете MaterialApp через параметр routes.

Теперь параметр home со значением MainScreen() – можно удалить.

Если нам нужно изменить маршрут по умолчанию, при открытии приложения, нужно указать параметр initialRoute со значением маршрута, к примеру: initialRoute: '/second'.

Для открытия окна по маршруту нужно использовать Navigator.pushNamed.

Сделаем замену кода открытия окна с использованием маршрута:

Для возвращения ничего менять в коде не надо, оставляем Navigator.pop(context);

Листинг кода, пример с маршрутами:

3. Передача параметров в маршруте с помощью события onGenerateRoute

Следующая проблема, которую нужно решить – это передача параметров в маршруте. Например мы хотим передавать, в некоторых случает, число во второй виджет.
К примеру с помощью такого маршрута '/second/123'.

Если в предыдущем примере мы вызовем маршрут '/second/123' – то мы ничего не откроем: такого маршрута нет. Так как прописать все такие маршруты невозможно, то мы должны добавить обработчик onGenerateRoute в виджете MaterialApp:

Маршрут '/second' в параметре routes можно было бы убрать, нужно только правильно написать исключение на отсутствие параметра path[2]. Но в нашем примере мы оставим его.

Листинг кода, пример с передачей параметров в маршруте:

4. Открытие диалогового окна

С помощью класса Navigator можно так же открывать диалоговые или всплывающие окна.

Создадим диалоговое окно с помощью виджет-класса PageRouteBuilder и параметром opaque: false.

Листинг кода, открытия диалогового окна:

5. Анимация диалогового окна

Открывающиеся окна можно проанимировать, для этого нужно добавить параметр transitionsBuilder в виджет PageRouteBuilder

Нижние подчеркивания играют роль переменных, т.е. вместо «_» и «__» можно было бы задать «varA» и «varB».

Так как мы не используем эти переменные, а в параметрах должны быть указаны названия для них – мы присвоили им названия «_» и «__», визуально они выглядят как прочерк.

  • FadeTransition – анимация прозрачности, opacity – текущие значение прозрачности
  • child – это виджет над которым будет производиться анимация

Интересным моментом является то что можно комбинировать анимации – как бы вкладывать их друг в друга.

Объединим две анимации: изменения прозрачности и увеличения размера.

6. Возвращаемое значение из диалогового окна

Чтобы получить какое-то значение из диалогового окна, нужно в функции pop после context добавить значение, которое мы будем возвращать. Тип значения может быть любым.
Для нашего примера пусть будет: Navigator.pop(context,true);

Но чтобы получить значение нужно добавить: await перед Navigator и async в RaisedButton:

Flutter Modal Bottom Sheet Tutorial

In this tutorial, we’ll demonstrate how to create a modal bottom sheet in Flutter with practical examples.

Here’s what we’ll cover:

Types of bottom sheets in Flutter

There are basically three types of Flutter bottom sheets: standard, modal, and expanding.

  1. Standard bottom sheets display supplemental content without restricting the user from interacting with the main part of the app while the sheet is visible. Standard bottom sheets are also known as persistent bottom sheets
  2. Modal bottom sheets show supplemental data while restricting users from interacting with other parts of the app. The user must dismiss the modal bottom sheet to continue interacting with the app’s main content
  3. Expanding bottom sheets are like a hybrid of standard and modal bottom sheets. An expanding bottom sheet enables the user to access both the standard sheet and information presented in the modal bottom sheet

For this tutorial, we’ll focus on creating a modal bottom sheet in Flutter.

What is a modal bottom sheet?

A modal bottom sheet is a widget, which is a core building block of Flutter apps, in Material Design.

Modal bottom sheets in Flutter are used to display supplementary content while restricting the user from interacting with the app’s main content. As the name suggests, a bottom sheet is positioned at the bottom of the screen.

Let’s say, for example, you have a photo saved in Google Photos that you want to share with a friend. When you tap the photo and click SHARE, some additional information shows up at the bottom of the screen:

Photo Share Options

The additional information that appears at the bottom of the screen is an example of a bottom sheet.

What is a modal bottom sheet used for?

The purpose of a modal bottom sheet is to create room for more content in your app. Modal bottom sheets are very common in mobile apps. They are often used to display links to other apps on the user’s mobile device.

We made a custom demo for .
No really. Click here to check it out .

As mentioned earlier, with a modal bottom sheet, interaction with other elements of the UI is blocked. Users can only interact with the other part of the app’s UI after dismissing (closing) the modal bottom sheet.

A modal bottom sheet will appear in response to some user action, such as tapping an icon. It can be dismissed by any of the following user actions:

  • Tapping an item within the bottom sheet
  • Tapping the main UI of the app
  • Swiping down

The showModalBottomSheet function

Modal bottom sheets can be created and displayed using the showModalBottomSheet function.

Let’s take a close look at the showModalBottomSheet function:

The showModalBottomSheet has two required properties: BuildContext and WidgetBuilder .

  1. BuildContext takes the context argument, which is used to look up the Navigator and the theme for the bottom sheet. This is used when the method is called
  2. The WidgetBuilder is a function that takes the current context — which, in this case, is the builder — and returns a widget. This widget is — you guessed it — a bottom sheet widget

How to create a modal bottom sheet in Flutter

To show the modal bottom sheet in action, we’re going to build a Flutter app with a button that, when clicked, displays a modal bottom sheet.

This tutorial assumes some basic knowledge of and experience building apps with Flutter.

First, start a new Flutter project on Android Studio (or any IDE of your choice). Name the project modalbottomdemo .

Clear the code except for import 'package:flutter/material.dart' , which we’ll use to import the Material Design component for the app and void main() => runApp(MyApp()); , which Flutter generates when a new project is created. We’re doing this because we want to build from the ground up.

You should have something like this in your editor:

Create a StatefulWidget that is extended by the MyApp() . Typing stfu + tab on your editor will automatically create a stateful widget.

Next, build the AppBar of the app using the Scaffold widget, which is like a container that houses the structure of your app (AppBar, body, side, etc.).

Now it’s time to create the body widget, which will contain a button, ElevatedButton , with the text, “Show Modal Bottom Sheet.” The button will be placed at the center of the app using the Center widget.

As stated earlier, we’ll use the showModalBottomSheet widget to display a modal bottom sheet, which takes two properties: context and the builder .

Run the app on any simulator of your choice. Here’s what our Flutter app looks like running on an iPhone 12 mini simulator:

Flutter Running iPhone Simulator

Clicking the button should bring up the hidden menu:

Hidden Menu Options

Here’s the complete code for this demo:

Conclusion

Flutter comes with customizable widgets that you can use to build cross platform apps for Android, iOS, and the web. With the showModalBottomSheet widget, you can create modal bottom sheets that enhance the user experience for those accessing your app on a mobile device.

You can learn more about Flutter by browsing through our collection of Flutter articles and tutorials.

LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

An alert dialog informs the user about situations that require acknowledgement. An alert dialog has an optional title and an optional list of actions. The title is displayed above the content and the actions are displayed below the content.

If the content is too large to fit on the screen vertically, the dialog will display the title and the actions and let the content overflow, which is rarely desired. Consider using a scrolling widget for content, such as SingleChildScrollView, to avoid overflow. (However, be aware that since AlertDialog tries to size itself using the intrinsic dimensions of its children, widgets such as ListView, GridView, and CustomScrollView, which use lazy viewports, will not work. If this is a problem, consider using Dialog directly.)

For dialogs that offer the user a choice between several options, consider using a SimpleDialog.

Typically passed as the child widget to showDialog, which displays the dialog.

This snippet shows a method in a State which, when called, displays a dialog box and returns a Future that completes when the dialog is dismissed.

This demo shows a TextButton which when pressed, calls showDialog. When called, this method displays a Material dialog above the current contents of the app and returns a Future that completes when the dialog is dismissed.

To create a local project with this code sample, run:
flutter create --sample=material.AlertDialog.2 mysample

    , which handles the scrolling of the contents but has no actions. , on which AlertDialog and SimpleDialog are based. , an iOS-styled alert dialog. , which actually displays the dialog and returns its result.

Constructors

Properties

actions → List < Widget > ? The (optional) set of actions that are displayed at the bottom of the dialog with an OverflowBar. [. ]

actionsAlignment → MainAxisAlignment? Defines the horizontal layout of the actions according to the same rules as for Row.mainAxisAlignment. [. ]

actionsOverflowAlignment → OverflowBarAlignment? The horizontal alignment of actions within the vertical "overflow" layout. [. ]

actionsOverflowButtonSpacing → double? The spacing between actions when the OverflowBar switches to a column layout because the actions don't fit horizontally. [. ]

actionsOverflowDirection → VerticalDirection? The vertical direction of actions if the children overflow horizontally. [. ]

actionsPadding → EdgeInsetsGeometry Padding around the set of actions at the bottom of the dialog. [. ]

clipBehavior → Clip Controls how the contents of the dialog are clipped (or not) to the given shape. [. ]

content → Widget? The (optional) content of the dialog is displayed in the center of the dialog in a lighter font. [. ]

insetPadding → EdgeInsets The amount of padding added to MediaQueryData.viewInsets on the outside of the dialog. This defines the minimum space between the screen's edges and the dialog. [. ]

semanticLabel → String? The semantic label of the dialog used by accessibility frameworks to announce screen transitions when the dialog is opened and closed. [. ]

title → Widget? The (optional) title of the dialog is displayed in a large font at the top of the dialog. [. ]

Methods

build ( BuildContext context ) → Widget Describes the part of the user interface represented by this widget. [. ]

createElement ( ) → StatelessElement Creates a StatelessElement to manage this widget's location in the tree. [. ]

debugDescribeChildren ( ) → List < DiagnosticsNode > Returns a list of DiagnosticsNode objects describing this node's children. [. ]

debugFillProperties ( DiagnosticPropertiesBuilder properties ) → void Add additional properties associated with the node. [. ]

noSuchMethod ( Invocation invocation ) → dynamic Invoked when a non-existent method or property is accessed. [. ]

Creating Dialogs in Flutter

You can see dialog on nearly every mobile application out there. Most applications use dialog to give an alert or facilitate intermediate action that is an alternative from the main flow of the application.

As an example, let’s say there is a submit button, and when the user presses submit, it shows a dialog to indicate the action is complete and to include instructions on the next steps. That is an intermediate action from the main flow.

Because dialogs are essential to mobile applications, Flutter facilitates alert and full-screen dialogs and also gives you the option to create custom dialogs. We’ll be covering these aspects of dialogs in Flutter:

Creating an alert dialog in Flutter

First of all, let’s create a simple dialog. The AlertDialog widget provides all the required functionalities to create a basic dialog in Flutter. The title and content properties should be specified to show a proper dialog. Neither of these is required, but you will not see any content or a title if you don’t specify these properties properly:

If you want to show an iOS-style dialog, you can use the CupertinoAlertDialog widget instead of the AlertDialog widget:

Now the question is, how can we show this dialog? That’s why we need to use the showDialog method, which helps to show the dialog above the current context of the application. This will take care of adding the dark, transparent layer when showing the dialog.

You can create a button ( ElevatedButton / TextButton ) and add the showDialog method like below in the onPressed method to show when you press the button:

Flutter AlertDialog

Flutter AlertDialog Cupertino

You can further customize the dialog by setting backgroundColor and titleTextStyle properties based on your need. But these properties will not be available in the CupertinoAlertDialog widget and are only available in the AlertDialog widget.

We made a custom demo for .
No really. Click here to check it out .

The default AlertDialog has a border radius of 4. The shape property gives you the flexibility to customize that value as you need. But CupertinoAlertDialog doesn’t allow the user to customize these properties, and you have to stick with the default values:

Flutter AlertDialog Background Color

Applying action buttons to a dialog

The AlertDialog widget can specify the action buttons that need to show in the dialog. These buttons will be shown at the bottom of the dialog.

There is no limit to the number of action buttons you can have. But it’s better to use 1–3 action buttons to give a good user experience and a less cluttered user interface:

Flutter AlertDialog Action Buttons

In the CupertinoAlertDialog , instead of the normal buttons, CupertinoDialogAction widgets have to be used inside the actions widget array:

Flutter CupertinoAlertDialog Action Widget

If your application requires more action buttons, you can add more based on your need. Those will stack as a column if there is no room to show in a single inline. If this overflow happens, you can control the button spacing by setting the actionsOverflowButtonSpacing property.

The actionsOverflowButtonSpacing property is only available in the AlertDialog widget and not available in CupertinoAlertDialog . In CupertinoAlertDialog , it usually shows a maximum of two buttons per row, and if there are more action buttons, those will be shown vertically:

Flutter AlertDialog with Multiple Action Buttons

Flutter CupertinoAlertDialog with Multiple Action Buttons

Closing and dismissing dialog

You can use the Navigator class to remove the dialog when you press a button:

Creating a custom dialog

The AlertDialog widget may not be suitable for every custom scenario that you are handling in your app. That’s when the Dialog widget comes in handy.

Even though the content property of AlertDialog accepts the widget type, it’s recommended to add only a simple dialog message, which means it’s not suitable for custom dialogs.

On the other hand, the Dialog widget can create a custom version of the dialog as you need. I have added a Container to control the dialog height, and inside the Container , there is a Column widget to lay out multiple widgets vertically. You can customize these widgets based on your need:

Flutter Custom Dialog

If you want to change the shape of the dialog, you can set the ShapeBorder for the shape property like the below example. Here I have used a RoundedRectangleBorder widget to change the border radius of the dialog:

Flutter Rounded Corner Custom Dialog

Dialog has a default elevation of 24. Elevation is the z coordinate of the dialog, and that can be changed by setting the elevation property of the dialog. If you set the elevation to 0, you can see there’s no shadow, and it shows both the dialogs and the views below that are on the same surface.

Flutter Dialog with No Shadow

For AlertDialog , dialog background color can be set by changing the backgroundColor property of the Dialog widget:

Flutter Dialog with a Green Background

Creating a full-screen dialog

Creating a full-screen dialog cannot be done by the showDialog method. Instead, use the showGeneralDialog method.

In the pageBuilder , you should specify your dialog widget implementation. As a first widget, you can specify the SizedBox.expand widget, which converts your normal dialog to full-screen dialog.

Other than the pageBuilder property, you can control the dialog animation duration through the transitionDuration property to give nice and smooth animation:

Conclusion

Applying an alert dialog, custom dialog, or full-screen dialog will totally depend on your application and the different use case of the application.

Alert dialogs are more suitable for quick and simple alerts to users like success messages or info alerts. Custom dialogs can be used in places that require more personalized dialog with multiple widgets. Full-screen dialogs can be used if you want to give the sense of a completely new screen to a user without actually navigating to a completely new screen.

Among these dialogs, custom dialogs will be the most useful because you can give your own personal touch for each dialog to make it look nice and cool while maintaining your application’s theme.

LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.


In the mobile apps, we use Dialog everywhere from alerting some situation to the user to get some feedback from the user.

We can use alert dialog to pause the user interaction with the current screen and show some intermediate action to the user like show error, take user email to process next step kind of stuff.

When comes to the Dialog in Flutter there are multiple ways of implement like

  1. Alert Dialog
  2. Custom Dialog
  3. Full-Screen Dialog

Adding simple Dialog to your screen in pretty easy in Flutter.

Before adding Dialog you must call showDialog function to change current screen state to show the intermediate Dialog popup.

In here we use AlertDialog widget to show simple Dialog with title and some text in the body.

Under the content, it does not required to add only the Text, you can add any widget like Image or something. But Because we use Alert Dialogs in simple use case, it better to show simple text or an image inside the content.

Add buttons to Alert Dialogs

In the AlertDialog widget, there is a parameter called action. ​It accepts arrays of widgets and you can provide multiple buttons to that. Those Buttons will appear in the bottom right corner of the dialog.

How to close Alert Dialogs

In here we need to close the current Dialog when clicking Close button.

We can use the pop method in Navigator class for that.

Simple Alert Dialog will not be useful for every requirement. If you want to implement more advanced custom Dialog, you can use Dialog widget for that. Instead of the AlertDialog , in here we return Dialog widget. The showDialog method will remain the same.

You can use a Container widget to set relevant height for the Dialog.

Set the round corner to the Dialog by setting RoundedRectangleBorder for the shape and provide radius as you need.

By Using showDialog method we cannot show full-screen Dialog. If we want to show dialog in full screen we must use showGeneralDialog method provided by Flutter SDK.

There are some interesting parameter available in showGeneralDialog method.

barrierColor — Change dropshadow outside the dialog.

transitionDuration — Animation duration

barrierDismissible — Dismiss dialog by clicking outside in current route

I hope you get a better idea about how to implement AlertDialog and How to convert that to a more customized version and how to show dialog in full screen.

Читайте также: