5

I have this widget tree

return Container(
  color: Colors.blue,
  child: Container(
    child: Text("Child"),
  ),
);

Is there a way to remove a parent widget from the tree or conditionally include it?

For example if a state variable such as includeBlueContainer was false, I would like to not render the blue container (but show everything else).

0

2 Answers 2

9

I couldn't achieve an optionally include reusable widget but I've been using this pattern which does achieve what I wanted to achieve. I haven't given this a great amount of thought but I still feel there is a better solution somewhere.

class MyContainer extends StatelessWidget {
  final Widget child;
  final bool isIncluded;
  MyContainer({this.child, this.isIncluded = true});

  Widget build(BuildContext context) {
    if (!isIncluded) return child;

    return Container(
      color: Colors.blue,
      child: child,
    );
  }
}
7

Edit: I made a package out of this: https://pub.dev/packages/conditional_parent_widget

Which you can use like:

import 'package:flutter/widgets.dart';
import 'package:conditional_parent_widget/conditional_parent_widget.dart';

// ...

return ConditionalParentWidget(
  condition: includeBlueContainer,
  child: Text("Child"),
  parentBuilder: (Widget child) => Container(
    color: Colors.blue,
    child: child,
  ),
);

Internally it is just:

import 'package:flutter/widgets.dart';

class ConditionalParentWidget extends StatelessWidget {
  const ConditionalParentWidget({
    Key? key,
    required this.condition,
    required this.child,
    required this.parentBuilder,
  }) : super(key: key);

  final Widget child;
  final bool condition;
  final Widget Function(Widget child) parentBuilder;

  @override
  Widget build(BuildContext context) {
    return condition ? this.parentBuilder(this.child) : this.child;
  }
}
3
  • 1
    Would be nice If you updated this package to also allow developers to conditionally use Parent A vs Parent B. Right now it is just parent A vs no parent. May 16 at 18:33
  • 1
    I forgot about this package, take a look here: github.com/ltOgt/ltogt_utils_flutter/blob/…
    – omnesia
    May 17 at 21:10
  • 2
    I did update the package now as well
    – omnesia
    May 17 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.