list_or 1.0.1 copy "list_or: ^1.0.1" to clipboard
list_or: ^1.0.1 copied to clipboard

A Dart utility that seamlessly normalizes single values and iterables into a unified, type-safe List.

example/list_or_example.dart

import 'package:list_or/list_or.dart';

void main() {
  print('--- Example 1: Wrapping a Single Value ---');
  // A single value is converted into a list containing just that value.
  final singleItem = ListOr<String>('Hello World');

  print('Length: ${singleItem.length}'); // Output: 1
  print('First item: ${singleItem[0]}'); // Output: Hello World

  // Notice the custom toString():it prints just the string, not ['Hello World']
  print('String representation: $singleItem'); // Output: Hello World

  print('\n--- Example 2: Wrapping an Iterable ---');
  // A standard List or Set is normalized into a modifiable ListOr.
  final multipleItems = ListOr<String>(['Apple', 'Banana']);

  // Because it mixes in ListMixin, you can use all standard list methods.
  multipleItems.add('Cherry');

  print('Length: ${multipleItems.length}'); // Output: 3

  // When the length is not exactly 1, toString() acts like a normal List.
  print(
    'String representation: $multipleItems',
  ); // Output: [Apple, Banana, Cherry]

  print('\n--- Example 3: Parsing Flexible JSON Data ---');
  // Imagine an API that irregularly returns 'tags' as either a String or a List.
  final Map<String, dynamic> jsonResponse1 = {'id': 1, 'tags': 'flutter'};
  final Map<String, dynamic> jsonResponse2 = {
    'id': 2,
    'tags': ['dart', 'backend'],
  };

  // ListOr cleanly normalizes both scenarios without complex type checking.
  final tags1 = ListOr<String>(jsonResponse1['tags']);
  final tags2 = ListOr<String>(jsonResponse2['tags']);

  print(
    'Tags 1 contains "flutter": ${tags1.contains('flutter')}',
  ); // Output: true
  print('Tags 2 length: ${tags2.length}'); // Output: 2

  print('\n--- Example 4: Handling Nulls with Nullable Types ---');
  // If your data might explicitly be null and you want to keep that null
  // as a valid single element, you must use a nullable generic type.
  final nullableList = ListOr<int?>(null);

  print('Nullable list length: ${nullableList.length}'); // Output: 1
  print('First item: ${nullableList.first}'); // Output: null

  // Note: Trying to do the following would throw an ArgumentError,
  // keeping your types safe:
  // final strictList = ListOr<int>(null); // THROWS!
}
0
likes
160
points
--
downloads

Documentation

API reference

Publisher

verified publisherhanskokx.com

Weekly Downloads

A Dart utility that seamlessly normalizes single values and iterables into a unified, type-safe List.

Repository
View/report issues

License

BSD-3-Clause (license)

More

Packages that depend on list_or