DEV Community

Cover image for Dart Extensions Make My Heart Flutter πŸ˜‡
Tornike
Tornike

Posted on • Updated on

Dart Extensions Make My Heart Flutter πŸ˜‡

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)
Enter fullscreen mode Exit fullscreen mode

Create extension on BuildContext

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

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;
}
Enter fullscreen mode Exit fullscreen mode

Or getting device top padding

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

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'),
   ));
 }
}
Enter fullscreen mode Exit fullscreen mode

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'),
   ));
 }
}
Enter fullscreen mode Exit fullscreen mode

Usage

import 'my_extensions.dart'
class CheckMyProfileWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final theme = context.theme;
    final textTheme = context.textTheme;
    final topPadding = context.topPadding;
    context.push(NewPage());
    return Container();
  }
}
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)