- PVSM.RU - https://www.pvsm.ru -
Начинаем новую неделю с очередной интерпретации официальной документации Flutter [1] в формате «вопрос-ответ». 4-я часть освещает в сравнительном стиле Flutter для веб-разработчиков. Она целиком посвящена вёрстке и вышла не такой объёмной, как предыдущие. Традиционно рекомендую всем интересующимся Flutter веб-разработчикам заглянуть под кат, чтобы понять, стоит ли пробовать этот фреймворк и сколько усилий это займёт.
![[По докам] Flutter. Часть 4. Для веб-разработчиков - 1 [По докам] Flutter. Часть 4. Для веб-разработчиков - 1](http://www.pvsm.ru/images/2020/02/04/po-dokam-Flutter-chast-4-dlya-veb-razrabotchikov.jpeg)
Если информации здесь будет недостаточно или у вас есть опыт в нативной разработке под конкретную платформу, то рекомендую заглянуть в другие части:
Flutter. Часть 1. Для Android-разработчиков [2]
Flutter. Часть 2. Для iOS-разработчиков [3]
Flutter. Часть 3. Для React Native-разработчиков [4]
Flutter. Часть 4. Для Web-разработчиков
Flutter. Часть 5. Для Xamarin.Forms-разработчиков
Как стилизовать и выравнивать текст?
С помощью TextStyle [23].
HTML/CSS
<div class="greybox">
Lorem ipsum
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Georgia;
}
Flutter
var container = Container( // grey box
child: Text(
"Lorem ipsum",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w900,
fontFamily: "Georgia",
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как устанавливается цвет фона?
С помощью класса BoxDecoration [24].
Свойство background-color в CSS отвечает только за цвет фона. BoxDecoration [24] отвечает за более широкий спектр свойств, например скругление углов, окантовку и т.п.
HTML/CSS
<div class="greybox">
Lorem ipsum
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
}
Flutter
var container = Container( // grey box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
width: 320,
height: 240,
decoration: BoxDecoration(
color: Colors.grey[300],
),
);
Как центрировать компоненты?
С помощью виджета Center [25].
HTML/CSS
<div class="greybox">
Lorem ipsum
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
Flutter
var container = Container( // grey box
child: Center(
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как установить ширину контейнера?
С помощью свойства width.
У виджетов Flutter свойство width фиксировано. Чтобы настроить maxWidth или minWidth, используется виджет BoxConstraints [26].
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
width: 100%;
max-width: 240px;
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
width: 240, //max-width is 240
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как устанавливать абсолютную позицию?
С помощью виджета Positioned [27] внутри виджета Stack [28].
По умолчанию виджеты позиционируются внутри родительских виджетов.
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
position: relative;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
position: absolute;
top: 24px;
left: 24px;
}
Flutter
var container = Container( // grey box
child: Stack(
children: [
Positioned( // red box
child: Container(
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
),
left: 24,
top: 24,
),
],
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как задавать вращение компонентам?
С помощью виджета Transform [29].
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
transform: rotate(15deg);
}
Flutter
var container = Container( // gray box
child: Center(
child: Transform(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
textAlign: TextAlign.center,
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
),
alignment: Alignment.center,
transform: Matrix4.identity()
..rotateZ(15 * 3.1415927 / 180),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как скейлить компоненты?
С помощью виджета Transform [29].
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
transform: scale(1.5);
}
Flutter
var container = Container( // gray box
child: Center(
child: Transform(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
textAlign: TextAlign.center,
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
),
alignment: Alignment.center,
transform: Matrix4.identity()
..scale(1.5),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как применить градиент?
С помощью класса BoxDecoration [24] и его свойства gradient.
Вертикальный линейный градиент
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
padding: 16px;
color: #ffffff;
background: linear-gradient(180deg, #ef5350, rgba(0, 0, 0, 0) 80%);
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: const Alignment(0.0, -1.0),
end: const Alignment(0.0, 0.6),
colors: <Color>[
const Color(0xffef5350),
const Color(0x00ef5350)
],
),
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Горизонтальный линейный градиент
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
padding: 16px;
color: #ffffff;
background: linear-gradient(90deg, #ef5350, rgba(0, 0, 0, 0) 80%);
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: const Alignment(-1.0, 0.0),
end: const Alignment(0.6, 0.0),
colors: <Color>[
const Color(0xffef5350),
const Color(0x00ef5350)
],
),
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как скруглять углы?
С помощью класса BoxDecoration [24] и его свойства borderRadius.
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* gray 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
border-radius: 8px;
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red circle
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
decoration: BoxDecoration(
color: Colors.red[400],
borderRadius: BorderRadius.all(
const Radius.circular(8),
),
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как добавить тень?
С помощью класса BoxShadow [30].
BoxShadow [30] используется в рамках свойства boxShadow класса BoxDecoration [24].
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.8),
0 6px 20px rgba(0, 0, 0, 0.5);
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: bold24Roboto,
),
decoration: BoxDecoration(
color: Colors.red[400],
boxShadow: [
BoxShadow (
color: const Color(0xcc000000),
offset: Offset(0, 2),
blurRadius: 4,
),
BoxShadow (
color: const Color(0x80000000),
offset: Offset(0, 6),
blurRadius: 20,
),
],
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
decoration: BoxDecoration(
color: Colors.grey[300],
),
margin: EdgeInsets.only(bottom: 16),
);
Как делать круглые и эллипсовидные формы?
С помощью enum-класса BoxShape [31].
BoxShape [31] используется в рамках свойства shape класса BoxDecoration [24].
HTML/CSS
<div class="greybox">
<div class="redcircle">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* gray 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redcircle {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
text-align: center;
width: 160px;
height: 160px;
border-radius: 50%;
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red circle
child: Text(
"Lorem ipsum",
style: bold24Roboto,
textAlign: TextAlign.center,
),
decoration: BoxDecoration(
color: Colors.red[400],
shape: BoxShape.circle,
),
padding: EdgeInsets.all(16),
width: 160,
height: 160,
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как регулировать расстояние между текстом?
С помощью класса TextStyle [23] и его свойств letterSpacing и wordSpacing.
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
letter-spacing: 4px;
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: Text(
"Lorem ipsum",
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w900,
letterSpacing: 4,
),
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как форматировать часть текста?
С помощью виджета RichText [32] и класса TextSpan [33].
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem <em>ipsum</em>
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
}
.redbox em {
font: 300 48px Roboto;
font-style: italic;
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: RichText(
text: TextSpan(
style: bold24Roboto,
children: <TextSpan>[
TextSpan(text: "Lorem "),
TextSpan(
text: "ipsum",
style: TextStyle(
fontWeight: FontWeight.w300,
fontStyle: FontStyle.italic,
fontSize: 48,
),
),
],
),
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
Как ограничить показ длинного текста?
С помощью совойств maxLines и overflow виджета Text [34].
HTML/CSS
<div class="greybox">
<div class="redbox">
Lorem ipsum dolor sit amet, consec etur
</div>
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Roboto;
display: flex;
align-items: center;
justify-content: center;
}
.redbox {
background-color: #ef5350; /* red 400 */
padding: 16px;
color: #ffffff;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Flutter
var container = Container( // grey box
child: Center(
child: Container( // red box
child: Text(
"Lorem ipsum dolor sit amet, consec etur",
style: bold24Roboto,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: EdgeInsets.all(16),
),
),
width: 320,
height: 240,
color: Colors.grey[300],
);
В конце декабря 2019 года, с выходом Flutter 1.12, поддержка веба перешла в стадию beta! И это отличная новость, означающая, что в недалёком будущем мы будем всё чаще встречать сайты, написанные на Flutter. Поэтому, если вы всё ещё в раздумьях, рекомендую попробовать этот фреймворк и надеюсь, что моя статья была полезной. А на сегодня у меня всё. Да не сломает Google ваш Chrome!
Автор: Дмитрий Васильев
Источник [35]
Сайт-источник PVSM.RU: https://www.pvsm.ru
Путь до страницы источника: https://www.pvsm.ru/framework/345498
Ссылки в тексте:
[1] официальной документации Flutter: https://flutter.dev/docs/get-started/flutter-for/web-devs
[2] Flutter. Часть 1. Для Android-разработчиков: https://habr.com/ru/company/funcorp/blog/442432/
[3] Flutter. Часть 2. Для iOS-разработчиков: https://habr.com/ru/company/funcorp/blog/477182/
[4] Flutter. Часть 3. Для React Native-разработчиков: https://habr.com/ru/company/funcorp/blog/484284/
[5] Базовая вёрстка: #basic
[6] Как стилизовать и выравнивать текст?: #style
[7] Как устанавливается цвет фона?: #background
[8] Как центрировать компоненты?: #center
[9] Как установить ширину контейнера?: #width
[10] Позиции и размеры: #positions_and_sizes
[11] Как устанавливать абсолютную позицию?: #absolute_position
[12] Как задавать вращение компонентам?: #rotate
[13] Как скейлить компоненты?: #scale
[14] Как применить градиент?: #gradient
[15] Форма: #shape
[16] Как скруглять углы?: #rounded_corners
[17] Как добавить тень?: #shadow
[18] Как делать круглые и эллипсовидные формы?: #circle
[19] Текст: #text
[20] Как регулировать расстояние между текстом?: #space
[21] Как форматировать часть текста?: #span
[22] Как ограничить показ длинного текста?: #overflow
[23] TextStyle: https://api.flutter.dev/flutter/painting/TextStyle-class.html
[24] BoxDecoration: https://api.flutter.dev/flutter/painting/BoxDecoration-class.html
[25] Center: https://api.flutter.dev/flutter/widgets/Center-class.html
[26] BoxConstraints: https://api.flutter.dev/flutter/rendering/BoxConstraints-class.html
[27] Positioned: https://api.flutter.dev/flutter/widgets/Positioned-class.html
[28] Stack: https://api.flutter.dev/flutter/widgets/Stack-class.html
[29] Transform: https://api.flutter.dev/flutter/widgets/Transform-class.html
[30] BoxShadow: https://api.flutter.dev/flutter/painting/BoxShadow-class.html
[31] BoxShape: https://api.flutter.dev/flutter/painting/BoxShape-class.html
[32] RichText: https://api.flutter.dev/flutter/widgets/RichText-class.html
[33] TextSpan: https://api.flutter.dev/flutter/painting/TextSpan-class.html
[34] Text: https://api.flutter.dev/flutter/widgets/Text-class.html
[35] Источник: https://habr.com/ru/post/486822/?utm_source=habrahabr&utm_medium=rss&utm_campaign=486822
Нажмите здесь для печати.