πŸ” Code generation for selectors of class fields that helps reduce repetitive code

Related tags

Widgets select
Overview

select

Code generation for selectors of class fields and enum cases that helps reduce repetitive code.

Index

About

select helps generate selector methods for any class that can be used anywhere where you would use a selector-lambda and pattern-matching for Enums that can replace switch/case to be less wordy.

This package is compatible with the amazing freezed code generator.

Motivation

Writing less code without a meaning helps a developer to focus on writing actual code. selectable helps you focus on writing business logic instead of distracting on things that can be automatically derived.

Classes

Selectors are widely used in Flutter and Dart. The most common places of usage are:

  • Iterable transformations and especially mappings
  • Stream transformations
  • The select method extension from Provider
  • Most of the selector-widgets, such as BlocSelector

Selector functions tend to be very repetitive, in the example function (state) => state.field, word state is repeated two times, and there are four symbols and two spaces. Overall, from 22 symbols, only 11 have a meaning, that is – state.field.

That's a great task for automation, and that's exactly what that package does. So instead of writing (model) => model.field, it is possible to write Model$.field with select.

Enums

Similarly, Enums suffer from the same issues of demanding to write some code that doesn't has any meaning at all. Consider the following example:

switch (theme) {
  case AppTheme.light:
    print('Light!');
    break;
  case AppTheme.dark:
    print('Dark!');
    break;
  case AppTheme.system:
    print('System!');
    break;
}

From 138 symbols, only a fraction actually contains any meaning. selectable allows to write code with the same meaning, but a lot more compact:

theme.when(
  light: () => print('Light!'),
  dark: () => print('Dark!'),
  system: () => print('System!'),
);

That's almost twice as little symbols with a lot more meaning.

Install

select is a code-generation package, so the typical generator-annotation-builder setup is used.

Used packages

Pubspec

And the pubspec.yaml should be extended as in following:

dependencies:
  freezed_annotation: ^0.1.0

dev_dependencies:
  build_runner: #latest version
  select: ^0.1.0

Usage

To generate selectors, two following criteria should be met:

  1. The class is marked with the @selectable annotation or the enum is marked with the @matchable annotation.
  2. File with the class/enum includes a generated code, part model.select.dart;.

Selectable class

The following example demonstrates a minimal useful definition of the selectable class.

import 'package:select_annotation/select_annotation.dart';

part 'user.select.dart';

@selectable
class User {
  final String name;
  final int age;

  const User(this.name, this.age);
}

selectable can (and probably should) be used in conjunction with the freezed generator and other annotations.

import 'package:select_annotation/select_annotation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.select.dart';
part 'user.freezed.dart';

@selectable
@immutable
@freezed
class User with _$User {
  const factory User(String name, int age) = _User;
}

With the given User model, a class with two static methods will be generated.

abstract class User$ {
  User$._();

  static String name(User user) => user.name;
  static int age(User user) => user.age;
}

And that's it – those selectors can be used in any way, that a regular anonymous selector is used.

Matchable enum

To generate matching extensions for a enum, besides including the generated code through part directive, it must be annotated with the @matchable annotation:

@matchable
enum AppTheme {
  light,
  dark,
  system,
}

The following enum would generate an extension with two methods:

extension $AppThemeMatcherExtension on AppTheme {
  T when<T>({required T Function() light, required T Function() dark, required T Function() system}) {
    switch (this) {
      case AppTheme.light:
        return light();
      case AppTheme.dark:
        return dark();
      case AppTheme.system:
        return system();
    }
  }

  T whenConst<T>({required T light, required T dark, required T system}) {
    switch (this) {
      case AppTheme.light:
        return light;
      case AppTheme.dark:
        return dark;
      case AppTheme.system:
        return system;
    }
  }
}

The first one strictly replaces the switch/case, by allowing to execute only the matched case, accepting only the description of the values or actions, while the second one acts more as a type hash table, creating everything in advance and, as the name suggests, should be used with constant values.

Examples

Down below are listed the most commonly used use-cases for selectors and their versions implemented with selectable.

Iterable

[User('Bob', 28)].map(User$.name);

Stream

Stream.fromIterable([User('Jade', 33)]).map(User$.age);

Provider

Widget build(BuildContext context) {
  final userName = context.select(User$.name);
  
  return ...;
}

Selector builder

Widget build(BuildContext context) => BlocSelector<UserBloc, UserModel, int>(
    selector: User$.age
    builder: ...,
  );

Icons

Icon(
  theme.whenConst(
    light: Icons.wb_sunny,
    dark: Icons.brightness_3,
    system: Icons.brightness_auto,
  ),
);

Widget mappings

Widget build(BuildContext context) => formStep.when(
    name: () => NameForm(initial: name),
    age: () => AgeForm(minimumAge: widget.minimumAge),
    email: () => const EmailForm(),
  );
You might also like...

A flutter package which will help you to generate pin code fields with beautiful design and animations

A flutter package which will help you to generate pin code fields with beautiful design and animations

A flutter package which will help you to generate pin code fields with beautiful design and animations. Can be useful for OTP or pin code inputs πŸ€“ πŸ€“

Dec 23, 2022

Fluttex is useful package for reduce coding time and coding simplicity.

Fluttex is useful package for reduce coding time and coding simplicity.

Easy and Fast coding using Fluttex Fluttex is a package that developed for flutter framework. flutter developers can use this package to reduce their

Feb 19, 2022

Redux Compact is a library that aims to reduce the massive amount of boilerplate that follows maintaining a Flutter Redux application.

Redux Compact Redux Compact is a library that aims to reduce the massive amount of boilerplate that follows maintaining a Flutter Redux application. T

Apr 8, 2022

Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

flutter_video_compress Generate a new path by compressed video, Choose to keep the source video or delete it by a parameter. Get video thumbnail from

Dec 8, 2022

Flutter video compress - Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

Flutter video compress - Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

flutter_video_compress Generate a new path by compressed video, Choose to keep the source video or delete it by a parameter. Get video thumbnail from

Dec 8, 2022

ReverseHand is a mobile application that was created with the vision of helping to reduce any power imbalances that consumers may face when seeking trade services.

ReverseHand is a mobile application that was created with the vision of helping to reduce any power imbalances that consumers may face when seeking trade services.

ReverseHand is a mobile application that was created with the vision of helping to reduce any power imbalances that consumers may face when seeking trade services. To achieve this, the mobile application allows consumers to make their needs for services known in the form of job listings, where tradesmen are able to place bids in order to be chosen and hired.

Nov 2, 2022

Create highly customizable, simple, and controllable autocomplete fields for Flutter.

Create highly customizable, simple, and controllable autocomplete fields for Flutter.

Field Suggestion Installing Depend on it Add this to your package's pubspec.yaml file: dependencies: field_suggestion: latest_version Install it Y

Oct 18, 2022

Flutter form fields designed to take much of the burden of form-related coding off the programmer's back β€” masks, validations, keyboard type, etc.

Flutter form fields designed to take much of the burden of form-related coding off the programmer's back β€” masks, validations, keyboard type, etc.

well_formed Contents Overview Getting Started Demo application References Overview Well-Formed Widget Fields - Well-Formed - is a collection of Flutte

Nov 2, 2022

Object-oriented package for validating Flutter form fields.

Object-oriented package for validating Flutter form fields.

formdator Contents Overview Getting Started List of Validators Categories Demo Application References Overview Form Validator β€” Formdator is a fully o

Oct 26, 2022

Input fields for Flutter standalone or within a form

Flutter Input Widgets - Standalone or within a Form β†’ flutter_input This package provides input widgets (fields) to manipulate data. The data to manip

Mar 14, 2021

A set of flutter formatters for text and input fields

A set of flutter formatters for text and input fields

A set of formatters for text and input fields. Not only it can format a phone number but also automatically detect a country dial code and the name of the country. It also can apply formatting for currencies e.g. you need to convert 100000 into a USD currency value representation.

Dec 12, 2022

Counter provider - App para practicar el disenio de layouts con widgets mas comunes containers, stacks, row/columns, text fields

Counter provider - App para practicar el disenio de layouts con widgets mas comunes containers, stacks, row/columns, text fields

App para practicar el disenio de layouts con widgets mas comunes containers, sta

Feb 16, 2022

Flutter textfield validation lets you validate different textform fields in your Flutter app

Flutter textfield validation lets you validate different textform fields in your Flutter app

Flutter textfield validation lets you validate different textform fields in your Flutter app

Sep 15, 2022

First Open Source Flutter based Beautiful Material Design Text fields.

First Open Source Flutter based Beautiful Material Design Text fields.

Pretty text field First Open Source Flutter based Beautiful Material Design Text fields.(More designed text fields coming soon.) Features [*] Compatib

Aug 29, 2022

A code generation tool based on Database. :construction: developing :construction:

A code generation tool based on Database. :construction:  developing :construction:

dbgen A code generation tool based on Database. Getting Started This project is a starting point for a Flutter application. A few resources to get you

Jun 8, 2022

Examples of Flutter Code Generation.

Examples of Flutter Code Generation.

Flutter Code Generation Examples Code generation packages/tools used in the app: flutter_localization/intl build_runner flutter_gen/flutter_gen_runner

Oct 11, 2022

Code generation for Flutter Padding widgets based on your constants

Paddinger Paddinger is a Flutter package to generate Padding widgets. Given a set of constants like: @paddinger const double PADDING_NORMAL = 8; A set

Oct 20, 2022

Allows Dart reflection using code generation/builder.

reflection_factory reflection_factory allows Dart reflection with an easy approach, even for third-party classes, using code generation portable for a

Oct 30, 2022
Comments
  • Add `maybeWhen` and `maybeWhenConst`

    Add `maybeWhen` and `maybeWhenConst`

    The method should have the following signature:

    T maybeWhen<T>({required T Function() orElse, T Function()? ...cases}) {}
    
    T maybeWhenConst<T>({required T orElse, T? ...cases}) {}
    
    opened by purplenoodlesoop 0
Owner
Yakov K.
@flutter connoisseur
Yakov K.
A simple Flutter widget library that helps us to select days in a week.

A simple Flutter widget library that helps us to select days in a week.

Shan Shaji 4 Oct 9, 2022
Helps to turn some popular widgets into Neumorphism style

Helps to turn some popular widgets into Neumorphism style. Features NeumorphicCard: a card with Neumorphism look and feel NeumorphicButton: implements

MinhHo 6 Jun 27, 2022
Flutter package which helps you to implement Ticket Widget in your app.

✨ Ticket Widget Flutter package which helps you to implement Ticket Widget in your app. The source code is 100% Dart, and it is an updated null safe v

Mujahid 7 Dec 30, 2022
React hooks for Flutter. Hooks are a new kind of object that manages a Widget life-cycles. They are used to increase code sharing between widgets and as a complete replacement for StatefulWidget.

English | PortuguΓͺs Flutter Hooks A Flutter implementation of React hooks: https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 Ho

Remi Rousselet 2.6k Dec 29, 2022
A code generator to write widgets as function without loosing the benefits of classes.

Widgets are cool. But classes are quite verbose: class Foo extends StatelessWidget { final int value; final int value2; const Foo({Key key, thi

Remi Rousselet 528 Dec 29, 2022
A package for flutter to use alert and toast within one line code.

easy_alert A package for flutter to use alert and toast within one line code. Getting Started Add easy_alert: to your pubspec.yaml, and run flutt

null 34 Jun 25, 2021
A widget with side-by-side source code view.

A widget with side-by-side source code view. Extracted from the flutter-catalog open-source app.

xwei 23 Aug 29, 2022
A Highly customizable Phone input Flutter widget that supports country code, validation and contact picker.

A Highly customizable Phone input Flutter widget that supports country code, validation and contact picker.

null 6 Jun 7, 2022
A new Flutter project. Use of Padding Class(Widget) and Card Class (Widget)

Use_Of_Card_And_Padding_Class A new Flutter project. Use of Padding Class(Widget) and Card Class (Widget) Getting Started This project is a starting p

Avinandan Bose 1 Mar 18, 2022