Matches

Collection of useful patterns for Dart

GitHub stars Twitter Follow

ToC

Installation

dart pub add matches

or

flutter pub add matches

Usage

Result

Result<int> result = Pending<int>();

await Future.delayed(Duration(seconds: 1));
result = Loading<int>();

await Future.delayed(Duration(seconds: 1));
result = Success(42)

final child = switch (result) {
  Success(value: var v) => Text('The number is $v'),
  Loading(progress: var p) => LinearProgressIndicator(value: p),
  Failure(exception: var e) => Text('Error: ${e.toString()}'),
  _ => const SizedBox()
};

Ordering

final random = Random();

final a = random.nextInt(10);
final b = random.nextInt(10);

final msg = switch (a.compare(b)) {
  Greater(difference: var d) => 'a is greater than b by $d',
  Less(difference: var d) => 'a is less than b by $d',
  Equal _ => 'a and b are equal',
};

print(msg);

compare method is available on int, double, num, String, Date via extension.

Maybe

switch (a) {
  case Just(value: final v): print(v);
  case Nothing: print('nothing');
}

Either

switch (a) {
  case Left(value: final v): print(v);
  case Right(value: final v): print(v);
}

These

switch (user) {
  case Both<User, Admin>(a: final customer, b: final admin): {
    applyAdminCoupon(admin.employeId);
  }
  case This<User>(value: final user): {
    verifyHasValidPaymentMethod(user)
  };
}

checkout();

GitHub stars Twitter Follow

LICENSE

Copyright 2023 Andrei Lesnitsky

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Libraries

matches