Skip to content

Instantly share code, notes, and snippets.

@rydmike
Created January 9, 2021 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rydmike/27370ed27110bfd7f809f82dd8498c5b to your computer and use it in GitHub Desktop.
Save rydmike/27370ed27110bfd7f809f82dd8498c5b to your computer and use it in GitHub Desktop.
Flutter: A builder that if the [condition] is true, will run its builder and the child will be wrapped by the builder, if false it just returns the child.
import 'package:flutter/material.dart';
/// Type definition for a builder function used by IfWrapper.
typedef IfWrapBuilder = Widget Function(BuildContext context, Widget child);
/// A builder that if the [condition] is true, will run its builder and the
/// child will be wrapped by the builder, if false it just returns the child.
///
/// A convenient way to wrap a widget with another widget, but only if
/// the condition is true. It can save you from having to define a large widget,
/// assign it to a Widget itself wrapped with another widget.
///
/// Widget widgetA = WidgetX(...);
/// if (condition) widgetA = WidgetY(child: widgetA);
///
/// Becomes:
/// IfWrapper(condition: condition,
/// builder: (context, child) {
/// return WidgetY(child: child) }
/// child: child
/// );
class IfWrapper extends StatelessWidget {
const IfWrapper({
Key key,
@required this.condition,
@required this.builder,
@required this.child,
this.ifFalse,
}) : super(key: key);
/// if [condition] evaluates to true, the builder will be run and the child
/// will be wrapped. If false, only the child is returned.
final bool condition;
/// How to display the widget if [condition] is true;
final IfWrapBuilder builder;
final IfWrapBuilder ifFalse;
/// The widget to be conditionally wrapped, it will be returned alone without
/// the wrapping Widget if [condition] is false.
final Widget child;
@override
Widget build(BuildContext context) {
if (condition) {
return builder(context, child);
} else if (ifFalse != null) {
return ifFalse(context, child);
} else {
return child;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment