Skip to content

micrusa/micru_fl_utils

Repository files navigation

micru_fl_utils

This package was built to reduce boilerplate code in my apps with useful extensions, functions, etc

Getting started

Install with flutter pub add micru_fl_utils and start using all extensions

Features

Date Time

  • DateTime.equalsDate(DateTime) => Checks whether day, month and year are equal in two DateTime instances
DateTime a = DateTime(2000, 1, 1, 23, 59)
DateTime b = DateTime(2000, 1, 1, 02, 23)
// a.equalsDate(b) is true

Mixins

  • LoadingStateMixin => Use it to add a "loading" state to a function, can be used to avoid granny clicks (for example).
class MyWidget extends StatefulWidget {
  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> with LoadingStateMixin {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: withLoading(() async {
        // The button will get disabled while the function is running
        await Future.delayed(Duration(seconds: 2));
      }),
      child: Text("Click me"),
    );
  }
}

Widget Extensions

  • Widget.withPadding(EdgeInsets) => Wraps the widget with a Padding widget
  • Widget.withSize({width, height}) => Wraps the widget with a SizedBox widget
  • Widget.centered() => Wraps the widget with a Center widget
  • Widget.expanded({flex}) => Wraps the widget with an Expanded widget
  • Widget.flexible({flex, fit}) => Wraps the widget with a Flexible widget

Num

  • num.toStringWithLimitedDecimals(maxDecimals) => Returns a String with maxDecimals decimals, removing trailing zeros

Num list/iterable

  • sum() => Returns the sum of all elements
  • avg({ifEmpty}) => Returns the average of all elements or ifEmpty value if empty
  • max({ifEmpty}) => Returns the maximum value or ifEmpty value if empty
  • min({ifEmpty}) => Returns the minimum value or ifEmpty value if empty
  • range({ifEmpty}) => Returns the range (max - min) or ifEmpty value if empty
  • median({ifEmpty}) => Returns the median value or ifEmpty value if empty
  • product({ifEmpty}) => Returns the product of all elements or ifEmpty value if empty
final list = [1,2,3];
final sum = list.sum(); // 6
final avg = list.avg(); // 2
final max = list.max(); // 3

List

  • toMap(keyGenerator) => Converts list to map where keys are generated by keyGenerator function
  • sortedByKey(key) => Returns new list sorted by given key function
  • sortedBy(comparator) => Returns new list sorted by given comparator
  • difference(other) => Returns elements present in this list but not in other
  • intersection(other) => Returns elements present in both lists
final list = [3, 1, 4, 2];
final sorted = list.sortedByKey((e) => e); // [1, 2, 3, 4]
final map = list.toMap((e) => 'key$e'); // {'key1': 1, 'key2': 2, ...}

final list1 = [1, 2, 3];
final list2 = [2, 3, 4];
final diff = list1.difference(list2); // [1]
final common = list1.intersection(list2); // [2, 3]

Misc

  • Object?.let(T Function(Object)) => Kotlin-styled let, to handle null values more easily
final String? a = "asd";

final int? length1 = a.let((it) => it.length);
// Is equivalent to
int? length2;
if(a != null) {
    length2 = a!.length
}

Map Extensions

  • Map.copy() => Returns a new map with the same keys and values
  • Map.addAll(map) => Adds all entries from the given map to this map
final map = {'name': 'John', 'age': 30};
final copiedMap = map.copy(); // Creates a new map: {'name': 'John', 'age': 30}
copiedMap['age'] = 31; // Original map remains unchanged

final additionalInfo = {'city': 'New York'};
copiedMap.addAll(additionalInfo); // Now contains {'name': 'John', 'age': 31, 'city': 'New York'}

TextEditingController Mixin

  • textEditingController(key, {text}) => Get or create a controller for the given key
  • initTextEditingControllers(data) => Initialize controllers from a map
  • Automatically disposes controllers to prevent memory leaks
class _MyFormState extends State<MyForm> with TextEditingControllerMixin {
  @override
  void initState() {
    super.initState();
    // Pre-populate controllers (optional)
    initTextEditingControllers({'name': 'John', 'email': 'john@example.com'});
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(controller: textEditingController('name')),
        TextField(controller: textEditingController('email')),
        // Create a new controller on-the-fly
        TextField(controller: textEditingController('phone', text: '+1 ')),
        ElevatedButton(
          onPressed: () {
            final name = textEditingController('name').text;
            print('Hello, $name!');
          },
          child: Text('Submit'),
        ),
      ],
    );
  }
}

About

Flutter utilities and extensions to reduce boilerplate code with commonly used functions.

Topics

Resources

License

Stars

Watchers

Forks

Languages