Created
June 29, 2020 14:50
-
-
Save ltOgt/3771c824fc1c8811f5ec1a81a9a4937b to your computer and use it in GitHub Desktop.
Flutter Widget to conditionally wrap a subtree with a parent without breaking the code tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/widgets.dart'; | |
/// Conditionally wrap a subtree with a parent widget without breaking the code tree. | |
/// | |
/// [condition]: the condition depending on which the subtree [child] is wrapped with the parent. | |
/// [child]: The subtree that should always be build. | |
/// [conditionalBuilder]: builds the parent with the subtree [child]. | |
/// | |
/// ___________ | |
/// Usage: | |
/// ```dart | |
/// return ConditionalParentWidget( | |
/// condition: shouldIncludeParent, | |
/// child: Widget1( | |
/// child: Widget2( | |
/// child: Widget3(), | |
/// ), | |
/// ), | |
/// conditionalBuilder: (Widget child) => SomeParentWidget(child: child), | |
///); | |
/// ``` | |
/// | |
/// ___________ | |
/// Instead of: | |
/// ```dart | |
/// Widget child = Widget1( | |
/// child: Widget2( | |
/// child: Widget3(), | |
/// ), | |
/// ); | |
/// | |
/// return shouldIncludeParent ? SomeParentWidget(child: child) : child; | |
/// ``` | |
/// | |
class ConditionalParentWidget extends StatelessWidget { | |
const ConditionalParentWidget({ | |
Key key, | |
@required this.condition, | |
@required this.child, | |
@required this.conditionalBuilder, | |
}) : super(key: key); | |
final Widget child; | |
final bool condition; | |
final Widget Function(Widget child) conditionalBuilder; | |
@override | |
Widget build(BuildContext context) { | |
return condition ? this.conditionalBuilder(this.child) : this.child; | |
} | |
} |
exactly what i needed, many thanks
Thanksss!!!
This is also available as a package btw
To anyone have to preserve the child/parent state without rebuilding every time the condition changes:
https://gist.github.com/Muhammed-Rahif/ce0080ea05c07d7cb9a5dde50b0f1ce2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Brilliant.