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
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();
}
}
And the list of extensions goes on⦠you can add extension on any class and create cool shortcuts and useful methods.
Top comments (0)