Skip to content

Instantly share code, notes, and snippets.

@huynguyennovem
Created April 24, 2023 16:22
Show Gist options
  • Save huynguyennovem/aa719bf1c048f766b03c9e246eeb6889 to your computer and use it in GitHub Desktop.
Save huynguyennovem/aa719bf1c048f766b03c9e246eeb6889 to your computer and use it in GitHub Desktop.
Conditionally rendering widget in Flutter

conditional_parent_widget.dart:

import 'package:flutter/material.dart';

class ConditionalParentWidget extends StatelessWidget {
  final bool condition;
  final Widget Function({Widget? child}) leftParent;
  final Widget Function({Widget? child}) rightParent;
  final Widget child;

  const ConditionalParentWidget({
    Key? key,
    required this.condition,
    required this.leftParent,
    required this.rightParent,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return condition ? rightParent(child: child) : leftParent(child: child);
  }
}

Usage:

ConditionalParentWidget(
  condition: _conditionalVariable,
  rightParent: ({child}) => MouseRegion(
    onEnter: (event) {},
    onExit: (event) {},
    child: child ?? const SizedBox.shrink(),
  ),
  leftParent: ({child}) => Dismissible(
    key: Key('key'),
    onDismissed: (direction) {},
    background: Container(
      color: Colors.redAccent,
      alignment: Alignment.centerRight,
      padding: const EdgeInsets.all(8.0),
      child: Text('Remove'),
    ),
    child: child ?? const SizedBox.shrink(),
  ),
  child: Container(color: Colors.blue),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment