License Platform

Pub Version Pub.dev Score Pub Likes Pub.dev Publisher Downloads

Build Status Issues Last Commit Contributors

๐Ÿงฐ Flutter Extension Utils

Extensions that just make sense.

A handy collection of Dart and Flutter extension methods to supercharge your development experience โ€” clean syntax, reusable logic, and expressive code, all in one lightweight package.

Designed to save you time, reduce boilerplate, and improve readability across widgets, strings, numbers, booleans, and BuildContext.

๐Ÿ”Œ Installation & Setup

The package can be installed using the command

flutter pub add mayr_extensions

And can then be imported using

import 'package:mayr_extensions/mayr_extensions.dart';

๐Ÿš€ Features

๐Ÿงฑ BuildContext Extensions

  • form โ€“ Easily access the nearest FormState using context.form.

  • navigator โ€“ Shorthand for Navigator.of(context).

  • overlay โ€“ Access the current OverlayState from the context.

  • scaffold โ€“ Retrieve the nearest ScaffoldState with context.scaffold.

ScaffoldMessenger

  • scaffoldMessenger โ€“ Quickly get the ScaffoldMessengerState for showing snackbars and more.

  • void showSnackBar(String content, {Duration? duration, SnackBarBehavior behavior = SnackBarBehavior.fixed}) - Quickly show a SnackBar without manually accessing ScaffoldMessenger.

Media Query

  • mediaQuery โ€“ Access MediaQueryData from context.

  • platformBrightness โ€“ Get the system's brightness setting (Brightness.dark or Brightness.light).

  • platformInDarkMode | platformInLightMode โ€“ Returns true based on the app's current brightness mode.

  • widgetSize โ€“ Get the rendered size of the widget associated with the context.

  • widgetHeight โ€“ Convenience getter for just the height of the widget.

  • widgetWidth โ€“ Convenience getter for just the width.

Media Query Orientation

  • orientation โ€“ Access the current screen orientation (portrait or landscape).

  • isLandscape / isPortrait โ€“ Easy checks for current orientation.

  • widgetShortestSide โ€“ Useful for responsive layouts based on the device's shortest screen edge.

  • isPhone โ€“ Returns true if the device is considered a phone.

  • isSmallTablet, isLargeTablet โ€“ Classify tablets based on width.

  • isTablet โ€“ Shortcut combining both small and large tablets.

  • isDesktop โ€“ Detects larger screens, typically desktops.


๐Ÿ—“๏ธ DateTime Extensions

โœ… Checkers

  • isAfternoon โ€“ Checks if the time is between 12:00 PM and 5:59 PM.

  • isMorning โ€“ Checks if the time is before 12:00 PM.

  • isEvening โ€“ Checks if the time is between 6:00 PM and 8:59 PM.

  • isNight โ€“ Checks if the time is after 9:00 PM.

  • isToday / isTomorrow / isYesterday โ€“ Quickly check the relation to the current day.

  • isSameDay(DateTime other) โ€“ Returns true if the date is the same calendar day as other.

  • isInPast / isInFuture โ€“ Check if the datetime is before or after now.

๐Ÿ”ง Manipulators

  • addDays(int) / addMonths(int) / addYears(int) โ€“ Add to the datetime.

  • addHours(int) / addMinutes(int) / addSeconds(int) โ€“ Add smaller units.

  • subDays(int) / subMonths(int) / subYears(int) โ€“ Subtract from the datetime.

  • subHours(int) / subMinutes(int) / subSeconds(int) โ€“ Subtract smaller units.

๐Ÿ”ข Age

  • toAge() โ€“ Convert the date to an age in years.

  • isAgeOlder(age) / isAgeYounger(age) / isAgeEqualTo(age) โ€“ Check against an age.

  • isAgeBetween(min, max) โ€“ Check if the age is within a given range.

๐Ÿง  Time to String

  • toFormat(String format) โ€“ Fully custom format using intl.

    Popular date and time formats included in the MayrDateTimeFormats class.

    Currently includes:

    • MayrDateTimeFormats.ukDate - dd/MM/yyyy
    • MayrDateTimeFormats.ukDateTime - dd/MM/yyyy HH:mm:ss
    • MayrDateTimeFormats.usDate - yyyy-MM-dd
    • MayrDateTimeFormats.usDateTime - yyyy-MM-dd HH:mm:ss
    • MayrDateTimeFormats.time - HH:mm:ss
    • MayrDateTimeFormats.timeNoSecs - HH:mm
  • toDayOrdinal() โ€“ Get the day of the month with ordinal (e.g. 1st, 22nd, 31st).

  • toTimeAgoString() โ€“ Human-readable "time ago" format (e.g. "2 days ago").

  • toTimeString() โ€“ Convert to time only (e.g. 14:35 or 14:35:59).

  • toShortDate() โ€“ Returns a short formatted date string (e.g. Apr 25, 2025).


โณ Duration Extensions

  • delay([callback]) โ€“ Delays execution for the given duration. Optionally accepts a callback to run after the delay.
// Example
await 2.seconds.delay(() {
  print('Delayed by 2 seconds');
});

๐ŸŒ€ Dynamic Extensions

  • nullOnDebug<T>() โ€“ Returns null only in debug mode; retains value in release/profile. Useful for testing nullable flows.

  • onlyOnDebug<T>() โ€“ Returns the value only in debug mode, otherwise null.

  • maybe<T>({double probability = 0.5}) โ€“ Randomly returns null based on the given probability (between 0.0 and 1.0). Great for simulating unreliable data in tests or dev mode.

    final value = 'Simulate me'.maybe(probability: 0.3);
    // Has a 30% chance of being null
    
  • orDefault(T fallback) - Returns the fallback value if the provided value is null


๐Ÿ–ผ๏ธ Image Extensions

  • circleAvatar({ ... }) โ€“ Quickly convert an ImageProvider to a CircleAvatar widget with full customisation options.
// Example
NetworkImage('https://example.com/pic.jpg').circleAvatar(radius: 40);

Parameters:

  • backgroundColor โ€“ Background colour of the avatar (default is transparent).
  • radius โ€“ Sets the circular radius of the avatar.
  • minRadius / maxRadius โ€“ Optional constraints.
  • foregroundColor โ€“ Colour for the foreground image.
  • onBackgroundImageError / onForegroundImageError โ€“ Handle image load failures.

๐Ÿ”ข Number Extensions

๐Ÿงฎ General Num Extensions

  • isEqual(otherNum) โ€“ Checks if two numbers are exactly equal.

  • isGreaterThan(otherNum) โ€“ Returns true if the number is greater.

  • isLessThan(otherNum) โ€“ Returns true if the number is less.

  • clampMin(min) โ€“ Clamps the number to a minimum value.

  • clampMax(max) โ€“ Clamps the number to a maximum value.

๐ŸŽฒ Random Generators

  • randomLess({min = 1.0}) โ€“ For int or double, generates a random value less than the current one, starting from the min.

  • randomMore(max) โ€“ Generates a random value greater than the current one, up to max.

10.randomLess(); // e.g. returns 3, 7, etc.
5.5.randomMore(10.0); // e.g. returns 6.23, etc.

๐Ÿ’ฐ Number Formatting

  • formatAsCurrency({locale, symbol, decimalDigits}) โ€“ Formats the number as currency.

  • formatAsDecimal({locale, decimalDigits}) โ€“ Formats the number as a decimal with specified precision.

  • formatAsNumber({locale}) โ€“ Formats as a regular number string.

1234.5.formatAsCurrency(locale: 'en_NG', symbol: 'โ‚ฆ'); // โ‚ฆ1,234.50

โฑ๏ธ Number to Duration

  • days, hours, minutes, seconds, milliseconds, microseconds โ€“ Shorthand for converting numbers to Duration.
// Example
await 2.seconds.delay(); // Waits for 2 seconds

๐Ÿ”ค String Extensions

โœ… Utilities

  • copyToClipboard() - Copies the string to clipboard.

  • matchesRegExp(regex) โ€“ Checks if the string matches a given regular expression.

  • toBool โ€“ Converts "true" or "false" to a boolean.

  • toDateTime() โ€“ Parses the string into a DateTime object. Returns null if parse fails

  • toRegExp() โ€“ Converts the string into a RegExp.

  • toUri() - Attempts to parse the string to a Uri

  • limit(maxLength, [overflow = "โ€ฆ"]) โ€“ Limits string length with optional overflow characters.

  • mask({start = 2, end = 2, maskChar = '*', maskLength}) โ€“ Masks the middle of the string, leaving edges visible.

    '08012345678'.mask(); // 08*******78
    '08012345678'.mask(maskLength: 2); // 08**78
    

๐ŸŽ€ Pretty Printing

  • prettyJson() โ€“ Formats a raw JSON string.

  • prettyXml() โ€“ Formats raw XML into readable indents.

  • prettyYaml() โ€“ Formats YAML strings prettily.

๐Ÿ”  Casing

  • camelCase โ€“ Converts string to camelCase.

  • capitalised โ€“ Capitalises the first letter of each word.

  • kebabCase โ€“ Converts string to kebab-case.

  • pascalCase โ€“ Converts string to PascalCase.

  • snakeCase โ€“ Converts string to snake_case.

  • titleCase โ€“ Converts string to Title Case.

'the big brown fox'.camelCase; // theBigBrownFox
'the big brown fox'.capitalised; // The big brown fox
'the big brown fox'.pascalCase; // TheBigBrownFox
'the big brown fox'.kebabCase; // the-big-brown-fox
'the big brown fox'.snakeCase; // the_-_big_-_brown_-_fox
'the big brown fox'.titleCase; // The Big Brown Fox

๐Ÿงช Case and Pattern Checkers

Case Checkers
  • isCamelCase

  • isPascalCase

  • isSnakeCase

  • isKebabCase

  • isTitleCase

  • isCapitalised

  • isUpperCase

  • isLowerCase

Pattern Checkers
  • isEmail

  • isURL

  • isUlid

  • isUuid

  • isSlug

  • isHexColor

  • isIPAddress

  • isNum โ€“ Validates numeric string

  • isAlphabetOnly

  • isNumericOnly


๐Ÿงฉ Widget Extensions

๐Ÿช„ Basic Transformations

  • center({heightFactor, widthFactor}) โ€“ Wraps widget in a Center.

  • expanded([flex = 1]) โ€“ Wraps widget in an Expanded.

  • flexible({flex = 1, fit = FlexFit.loose}) โ€“ Wraps widget in a Flexible.

  • opacity(opacity) โ€“ Wraps widget with an Opacity widget.

  • sizedBox({width, height}) โ€“ Wraps widget with a SizedBox.

  • constrained({maxHeight, maxWidth, minHeight, minWidth}) โ€“ Wraps widget with a ConstrainedBox.


โœ‚๏ธ Clipping

  • clipRect() โ€“ Clips widget to a rectangle.

  • clipRRect(borderRadius) โ€“ Clips widget with rounded corners.

  • clipRounded([radius = 12]) โ€“ Quickly clip widget with a uniform rounded border.


๐Ÿงน Padding

  • paddingAll(padding) โ€“ Adds equal padding on all sides.

  • paddingSymmetric({horizontal, vertical}) โ€“ Adds symmetric horizontal and vertical padding.

  • paddingOnly({left, top, right, bottom}) โ€“ Custom padding for specific sides.

  • paddingZero() โ€“ Adds zero padding.


๐Ÿงญ Positioning

  • positionAlign(alignment) โ€“ Aligns widget using Align.

  • positionedFill() โ€“ Fills parent constraints using Positioned.fill.


๐Ÿ‘ป Visibility Helpers

  • hideIf(condition) โ€“ Hides widget (returns SizedBox.shrink()) if condition is true.

  • hideUnless(condition) โ€“ Hides widget unless condition is true.

  • showIf(condition) โ€“ Shows widget if condition is true, otherwise hides.

  • showUnless(condition) โ€“ Shows widget unless condition is true.


๐Ÿ”˜ inkwellManager on Widget

A helper class for managing taps on a widget in a cleaner way.

  • inkWellManager(callback, {color = Colors.transparent}) โ€“ Wraps widget with an InkWell for tap detection.

  • onTap() โ€“ Wraps child with InkWell for tap gesture.

  • onDoubleTap() โ€“ Wraps child with InkWell for double-tap gesture.

  • onLongPress() โ€“ Wraps child with InkWell for long-press gesture.

Tip: Used alongside the inkWellManager extension to easily attach tap interactions without boilerplate.

Text('Click Me')
  .inkWellManager(() => print('Tapped'), color: Colors.black)
  .onTap();
๐Ÿ’ก Why InkWellManager?

Normally, to make a widget respond to taps, you must manually wrap it inside an InkWell every time, setting colours and callbacks. InkWellManager simplifies this by providing quick .onTap(), .onDoubleTap(), and .onLongPress() methods โ€” making your code shorter, cleaner, and more maintainable.

It also auto-applies the same splash, hover, and focus colours without extra setup.

๐Ÿ“œ DateTimeFormat

This package also include some common date time formats. These inlude:

  • MayrDateTimeFormats.ukDate
  • MayrDateTimeFormats.usDate
  • MayrDateTimeFormats.time
  • MayrDateTimeFormats.timeNoSecs
  • MayrDateTimeFormats.ukDateTime
  • MayrDateTimeFormats.usDateTime

Usage

To use, simply import the package into your project and you can then all of the extensions it provdes ๐Ÿซถ๐Ÿพ

import 'package:mayr_extensions/mayr_extensions.dart';

๐Ÿ“ข Additional Information

๐Ÿค Contributing

Contributions are highly welcome! If you have ideas for new extensions, improvements, or fixes, feel free to fork the repository and submit a pull request.

Please make sure to:

  • Follow the existing coding style.
  • Write tests for new features.
  • Update documentation if necessary.

Let's build something amazing together!


๐Ÿ› Reporting Issues

If you encounter a bug, unexpected behaviour, or have feature requests:

  • Open an issue on the repository.
  • Provide a clear description and steps to reproduce (if it's a bug).
  • Suggest improvements if you have any ideas.

Your feedback helps make the package better for everyone!


๐Ÿ“œ Licence

This package is licensed under the MIT License โ€” which means you are free to use it for commercial and non-commercial projects, with proper attribution.

See the LICENSE file for more details.


๐ŸŒŸ Support

If you find this package helpful, please consider giving it a โญ๏ธ on GitHub โ€” it motivates and helps the project grow!

You can also support by:

  • Sharing the package with your friends, colleagues, and tech communities.
  • Using it in your projects and giving feedback.
  • Contributing new ideas, features, or improvements.

Every little bit of support counts! ๐Ÿš€๐Ÿ’™

Libraries

mayr_extensions