Last active
October 1, 2020 13:20
-
-
Save guid-empty/bcd5f3790f01da92102164f14236708a to your computer and use it in GitHub Desktop.
Collection If operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Подумайте, как можно было бы упростить метод build()? | |
Попробуйте самостоятельно или посмотрите solution |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
/// Flutter Mobile Developer | |
/// "collection if" operator | |
/// Вы разработчик библиотеки Flutter! | |
/// Это просто базовый класс для всех виджетов | |
abstract class BaseWidget {} | |
/// Это ваши конкретные виджеты, сейчас не имеет значения какие | |
class BalanceWidget implements BaseWidget {} | |
class SecretInfoWidget implements BaseWidget {} | |
class PaidAccountDetails implements BaseWidget {} | |
/// А вот это класс бизнес-логики | |
/// Вы разработчик класс Widget. | |
/// Класс будет сложный, это будет контейнер, | |
/// который внутри себя будет содержать | |
/// другие экземпляры класса Widget. | |
/// Поэтому вы в контракте класса выделили поле children - для дочерних виджетов. | |
class Widget implements BaseWidget { | |
final Iterable<BaseWidget> children; | |
Widget({@required this.children}); | |
} | |
/// | |
/// В этом коде мы создаем экземпляр класс Widget, используя функцию build() | |
/// | |
void main() { | |
final widget = build(); | |
print(widget); | |
} | |
/// | |
/// В методе build мы решаем, какие дочерние виджеты | |
/// будут включены в родительский. При этом мы начинаем учитывать условия, | |
/// согласно которым тот или иной виджет будет включен в список дочерний - | |
/// например, наличие прав, или ненулевой баланс, или подписка - да что угодно | |
/// | |
Widget build() { | |
final myBalance = 10; | |
final hasPermission = false; | |
final isPaidAccount = true; | |
final childrenWidgets = <BaseWidget>[]; // [] это литерал для объявления инстанса класса List обобщенного типом BaseWidget | |
/// при формировании списка дочерних элементов начинаем учитывать флаги | |
/// и вот кажется, что большие кол-во таких if убивает всю читаемость кода | |
if (myBalance > 0) { | |
childrenWidgets.add(BalanceWidget()); | |
} | |
if (hasPermission) { | |
childrenWidgets.add(SecretInfoWidget()); | |
} | |
if (isPaidAccount) { | |
childrenWidgets.add(PaidAccountDetails()); | |
} | |
return Widget(children: childrenWidgets); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
/// Flutter Mobile Developer | |
/// "collection if" operator | |
/// Вы разработчик библиотеки Flutter! | |
/// Это просто базовый класс для всех виджетов | |
abstract class BaseWidget {} | |
/// Это ваши конкретные виджеты, сейчас не имеет значения какие | |
class BalanceWidget implements BaseWidget {} | |
class SecretInfoWidget implements BaseWidget {} | |
class PaidAccountDetails implements BaseWidget {} | |
/// А вот это класс бизнес-логики | |
/// Вы разработчик класс Widget. | |
/// Класс будет сложный, это будет контейнер, | |
/// который внутри себя будет содержать | |
/// другие экземпляры класса Widget. | |
/// Поэтому вы в контракте класса выделили поле children - для дочерних виджетов. | |
class Widget implements BaseWidget { | |
final Iterable<BaseWidget> children; | |
Widget({@required this.children}); | |
} | |
/// | |
/// В этом коде мы создаем экземпляр класс Widget, используя функцию build() | |
/// | |
void main() { | |
final widget = build(); | |
print(widget); | |
} | |
/// | |
/// В методе build мы решаем, какие дочерние виджеты | |
/// будут включены в родительский. При этом мы начинаем учитывать условия, | |
/// согласно которым тот или иной виджет будет включен в список дочерний - | |
/// например, наличие прав, или ненулевой баланс, или подписка - да что угодно | |
/// | |
Widget build() { | |
final myBalance = 10; | |
final hasPermission = false; | |
final isPaidAccount = true; | |
/// collection if operator сильно уменьшает кол-во вызовов методов add(), addAll() и повышает читаемость кода - особенно в контексте Flutter | |
return Widget(children: [ | |
if (myBalance > 0) BalanceWidget(), | |
if (hasPermission) SecretInfoWidget(), | |
if (isPaidAccount) PaidAccountDetails(), | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment