safe area flutter что это

SafeArea in Flutter

SafeArea is an important and useful widget in Flutter which makes UI dynamic and adaptive to a wide variety of devices. While designing the layout of widgets, we consider different types of devices and their pre-occupied constraints of screen like status bar, notches, navigation bar, etc. But new devices are being launched with different designs and in certain scenarios, your app might overlay any of those pre-occupied constraints. So, in order to make our UI adaptive and error-free, we use SafeArea widget.

In simple words, SafeArea is basically a padding widget, which adds any necessary padding to your app, based on the device it is running on. If your app’s widgets are overlaying any of the system’s features like notches, status bar, camera holes, or any other such features, then SafeArea would add padding around the app, as required.

Internally SafeArea uses MediaQuery to check the dimensions of the display screen and includes extra padding if needed.

Constructor :

Above shown is the constructor for SafeArea. You can decide whether to avoid intrusions in a particular direction by changing the boolean value to true or false.

For instance, you want to use SafeArea in only top and bottom directions, then you can specify in following way.

The above code would add padding only at top and bottom while other directions (left and right) would remain unaffected. If you don’t specify any directions, then the default would be true for all directions.

If you want to add minimum padding in any of the directions, you can do it in the following way:

In the above code snippet, we are specifying the minimum padding that we need to add in all the directions. If you don’t specify this Flutter would automatically calculate the required padding for all the directions.

Explanation :

Now we’ll see how the above-mentioned properties work and when to use them.

Suppose, you are displaying a Text widget or any other widget at the bottom end of the screen, then on your device it might work, but on other devices, it might not be properly formatted.

Refer to the below screenshot to verify above mentioned scenario.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

You can see that in the above app the text widget is not properly formatted. The above-shown device is rectangular in shape, but if you test the same app on an iOS device, then the text might cover the app drawer. As a developer, your app should be free from all bugs on all devices. In this case, we will use SafeArea.

Refer to below example :

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

In the above example, we have used minimum property. Here, minimum padding of 12 is added to all the sides, as all directions (top, bottom, right, left) are true by default.

If you want to use SafeArea in particular direction, then you can do it in the following way :

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

In the above example, we can see that all directions are set to true except left and hence SafeArea is not used in that direction.

Источник

Flutter

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Виджет Flutter SafeArea

SafeArea — это, по сути, прославленный виджет Padding. Если вы обернете другой виджет с помощью SafeArea, он добавит все необходимые элементы, чтобы ваш виджет не был заблокирован системной строкой состояния, вырезами, отверстиями, закругленными углами и другими «творческими» особенностями производителей.

Что именно делает виджет SafeArea?

Мобильные устройства больше не имеют форму прямоугольника. Различные углы и вырезы делают дизайн приложения немного сложным. SafeArea — это виджет, который вставляет своего дочернего элемента с достаточным отступом, чтобы избежать вторжения операционной системы. Например, он отступит от дочернего элемента, чтобы избежать строки состояния в верхней части экрана. Давайте рассмотрим iPhone X, SafeArea будет стремиться избежать отображения контента в верхней части iPhone X. Однако эта функция применима к любому устройству с креативным дисплеем.

Вот пример без установленной SafeArea:

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Зачем он нам нужен?

Иногда мы можем захотеть отобразить ценную информацию в верхней или нижней части экрана. Однако все зависит от мобильного устройства. Иногда содержимое может отображаться корректно, а иногда его может нарушить операционная система устройства, например iPhone X. Поэтому для отображения текста лучше использовать виджет SafeArea.

Обернутый в виджет SafeArea:

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Когда его использовать?

Используйте виджет SafeArea только тогда, когда вы хотите отобразить содержимое представления списка или отдельного виджета в верхней или нижней части экрана. Это также позволит ребенку избежать выреза на iPhone-X или любых других подобных творческих физических особенностей дисплея.

Как его использовать?

SafeArea использует MediaQuery для проверки размеров экрана и подгонки под экран. Давайте рассмотрим на примере, как можно обернуть код в SafeArea:

С помощью простой команды вы можете защитить свой контент как на IOS, так и на Android.

Вы можете установить минимальное значение для краев, не затронутых надрезами и т.п:

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Вы также можете отключить вставки безопасной зоны для любой стороны:

Установка для них всех значения false будет равносильна отказу от использования SafeArea. По умолчанию для всех сторон установлено значение true. В большинстве случаев вам не понадобится использовать эти настройки, но я могу представить ситуацию, когда у вас есть виджет, который заполняет весь экран. Вы хотите, чтобы верхняя часть не была ничем заблокирована, но нижняя часть вас не волнует. В этом случае вы просто установите значение bottom: false, а для остальных сторон оставите значения по умолчанию true.

И вы даже можете обернуть свое тело в scaffold:

Источник

How to Create a Transparent SafeArea in Flutter with ColorfulSafeArea

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Apr 13, 2020 · 3 min read

Flutter’s SafeArea widget is a handy way to make sure that your UI doesn’t get cut off by any of the notches and curves that are now very common in smartphone screens.

However, it is not very customizable. What if you want to change the color of a SafeArea? You have to wrap it in a Container and set the Container’s color. What if you want the SafeArea to be transparent with UI underneath it? Then you’ll have to implement some sort of Stack of widgets.

ColorfulSafeArea 🎨

I didn’t like h aving to do that, so I created a Flutter package called ColorfulSafeArea that allows for easy customization of the colors of a SafeArea. It functions much like a regular SafeArea does.

Example

In this example, I have a Scaffold with a blue background and a ListView of red Containers wrapped in a ColorfulSafeArea. The result is what you would expect from a standard SafeArea widget. It adds padding near the notch.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

With Color 🖍

Don’t want the padding on the top to be same color as the Scaffold? Let’s give the ColorfulSafeArea widget a different color.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

With Transparency 🧊

Let’s try a color that has transparency. This time we set the color of the ColorfulSafeArea to white with some transparency. Notice how we can see the blue background of the Scaffold underneath the SafeArea.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

As an Overlay 🙈

That’s cool, but maybe you want to be able to see those red Containers underneath the ColorfulSafeArea. To make the ColorfulSafeArea widget behave like an overlay, we have to set the overflowRules, which are used to tell the ColorfulSafeArea which parts of its child are allowed to overflow underneath it. By setting the overflow rules for all sides to true, the child is allowed to overflow and we can now see it beneath our ColorfulSafeArea.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

In Summary

And that’s it! You now have a transparent safe area that behaves as an overlay. For more information on how to use this widget, check out the project’s github page here.

Источник

Как создать прозрачный SafeArea

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Однако у него очень мало настроек. Что делать, если вы хотите изменить цвет SafeArea? Вы должны обернуть его в Container и установить цвет контейнера. Но что, если вы хотите, чтобы SafeArea был прозрачным, а пользовательский интерфейс был виден под ним?

Нам на помощь приходит пакет colorful_safe_area позволяющий легко настраивать цвета в SafeArea.

Добавьте этот пакет в ваш pubspec.yaml файл:

Простой пример

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что этоColorfulSafeArea без цвета

Не хотите, чтобы отступ сверху был того же цвета, что и фон? Придадим виджету ColorfulSafeArea другой цвет.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что этоColorfulSafeArea с цветом

Прозрачность

Давайте попробуем использовать прозрачность. На этот раз мы установим для ColorSafeArea белый цвет с некоторой прозрачностью. Обратите внимание, что мы можем видеть синий фон скаффолда под SafeArea.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что этоColorfulSafeArea с эффектом прозрачности

Наложение

Это круто, но, возможно, вы захотите увидеть эти красные контейнеры под ColorfulSafeArea. Чтобы виджет ColorfulSafeArea вел себя как наложение, мы должны установить правила overflowRules, которые используются, чтобы сообщать ColorfulSafeArea, каким частям его дочернего элемента разрешено отрисовываться под ним. Установив для правил наложения, для всех сторон, значение true, разрешаем дочернему элементу наложение. И теперь мы можем видеть контейнеры под ColorfulSafeArea.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что этоColorfulSafeArea с эффектом наложения

Вот и все! Теперь у вас есть прозрачный SafeArea.

Источник

Make SafeArea Responsive in Flutter – Responsive Widget Tutorial

Trending Tutorials

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Without the SafeArea

Imagine we’re building an app without an app bar. The purpose of the app is to display a message across one half of the available space. At first, we might develop the following code which, however, doesn’t look right on the screen.

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Content is behind the status bar

main.dart

Adding a SafeArea

Being battle-tested Flutter developers, we know how to make sure that no content is displayed behind a status bar. Just add a SafeArea and call it a day, right?

main.dart

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Status bar is no longer covering with the content

I know, this may seem trivial, but when you’re handed absolutely precise design specs from a designer, following them to the tee is a must! Unless you enjoy heated design-related arguments, of course 😜

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

main.dart

ResponsiveBuilder

Firstly, let’s define the signature of the custom builder method. To keep it Flutter-compliant, we definitely want to pass down the BuildContext and, of course, it has to have a Size parameter.

responsive_safe_area.dart

Now we have a way to pass around the safe area’s size, how can we actually obtain it though?

Obtaining the available size

layout_builder_example.dart

safe area flutter что это. Смотреть фото safe area flutter что это. Смотреть картинку safe area flutter что это. Картинка про safe area flutter что это. Фото safe area flutter что это

Let’s put it all into practice together with a SafeArea and the ResponsiveBuilder method:

responsive_safe_area.dart

Using the ResponsiveSafeArea

responsive_safe_area.dart

And now, the container truly does take up only a half of the screen 🎉

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a Flutter freelancer and most importantly developer educator, he doesn’t have a lot of free time 😅 Yet he still manages to squeeze in tough workouts 💪

You may also like

Create Responsive Flutter Apps with Minimal Effort

Flutter Bottom Navigation with Nested Routing

Flutter AdMob Monetization – Banner and Interstitial Ads

I came across this, because I was irritated by the fact that I could not use a Column inside a Slider. I needed the slider for showing a keyboard without the yellow error lines…

I thought that SafeArea would be my key, as I had hoped that this would give me a box with fixed height and width. Alternative could be to give my app component fixed height, but that would have been annoying when going landscape (I think, anyway…)

Reso Coder is the place for your professional growth as a developer. Learn from project-based tutorials that are not afraid to cover important, yet often overlooked, topics such as good code architecture, testing and even deployment.

Join 15,000+ growth-oriented Flutter developers subscribed to the newsletter who receive weekly Flutter news and resources.

© 2021 Reso Coder Labs s.r.o.

Please log in again. The login page will open in a new tab. After logging in you can close it and return to this page.

Hey! We are required to tell you that we use cookies to enhance your experience.

Strictly Necessary Cookies

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *