Written by: Tornike Kurdadze | Sun Jan 01 2023 Flutter Extensions

Until Dart 2.7 introduced Extension methods, it was often impractical or impossible to add some functionality to built-in classes or someone else’s API.

Well, now you can, and here are some useful examples.

Tired of calling

final theme = Theme.of(context)

Create extension on BuildContext

extension BuildContextExt on BuildContext {
  /// Usage: context.theme;
  ThemeData get theme => Theme.of(this);
}

You probably need to get textTheme

extension BuildContextExt on BuildContext {  
 /// Usage: context.theme; 
 ThemeData get theme => Theme.of(this);
 /// Usage: context.textTheme;
 TextTheme get textTheme => theme.textTheme;
}

Or getting device top padding

extension BuildContextExt on BuildContext {  
 /// Usage: context.topPadding; 
 double get topPadding {
  return MediaQueryData.fromWindow(window).padding.top;
 }
}

Or pushing a new page

extension BuildContextExt on BuildContext {  
 /// Usage: context.push(NewPage()); 
 Future push(Widget page) {
   return Navigator.of(this).push(CupertinoAppRoute(
     builder: (_) => page,
     settings: RouteSettings(name: '$page'),
   ));
 }
}

Wrap everything in one extension.

extension BuildContextExt on BuildContext {  
 /// Usage: context.theme; 
 ThemeData get theme => Theme.of(this);

 /// Usage: context.textTheme;
 TextTheme get textTheme => theme.textTheme;

 /// Usage: context.topPadding; 
 double get topPadding {
  return MediaQueryData.fromWindow(window).padding.top;
 }
 
 /// Usage: context.push(NewPage()); 
 Future push(Widget page) {
   return Navigator.of(this).push(CupertinoAppRoute(
     builder: (_) => page,
     settings: RouteSettings(name: '$page'),
   ));
 }
}

Usage

final theme = context.theme;
final textTheme = context.textTheme;
final topPadding = context.topPadding;
context.push(NewPage());

And the list of extensions goes on… you can add extension on any class and create cool shortcuts and useful methods.

Coffee makes me feel like I have my shit together 😀, so here you go 💙