控制一个组件显示或隐藏 可设置隐藏后的占位组件。与其功能相似的由OffStage组件。

相关组件

Offstage

根据visible控制内部子组件的显隐情况

【visible】 : 是否显示 【bool】
【child】: 孩子 【Widget】
默认孩子隐藏时会失去原来所在区域。
image.png

  1. import 'package:flutter/material.dart';
  2. class CustomVisibility extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. return Wrap(
  6. spacing: 10,
  7. children: <Widget>[
  8. _buildVisibility(true),
  9. _buildVisibility(false),
  10. ],
  11. );
  12. }
  13. _buildVisibility(bool visible) {
  14. var box = Container(
  15. height: 30,
  16. width: 30,
  17. color: Colors.blue,
  18. );
  19. return Container(
  20. width: 150,
  21. height: 150 * 0.618,
  22. color: Colors.cyanAccent.withAlpha(33),
  23. child: Row(
  24. mainAxisAlignment: MainAxisAlignment.center,
  25. children: <Widget>[
  26. box,
  27. Visibility(
  28. visible: visible,
  29. child: Container(
  30. alignment: Alignment.center,
  31. height: 80 * 0.618,
  32. width: 80,
  33. color: Colors.red,
  34. child: Text(
  35. "visible\ntrue",
  36. style: TextStyle(fontSize: 20),
  37. ),
  38. )),
  39. box,
  40. ],
  41. ),
  42. );
  43. }
  44. }

replacement可在隐藏时进行占位

【replacement】 : 隐藏时的占位组件 【Widget】
image.png

import 'package:flutter/material.dart';
class ReplacementVisibility extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 10,
      children: <Widget>[
        _buildVisibility(true),
        _buildVisibility(false),
      ],
    );
  }

  _buildVisibility(bool visible) {
    var box = Container(
      height: 30,
      width: 30,
      color: Colors.blue,
    );
    return Container(
      width: 150,
      height: 150 * 0.618,
      color: Colors.cyanAccent.withAlpha(33),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          box,
          Visibility(
              visible: visible,
              replacement: Container(
                alignment: Alignment.center,
                height: 80 * 0.618,
                width: 80,
              ),
              child: Container(
                alignment: Alignment.center,
                height: 80 * 0.618,
                width: 80,
                color: Colors.red,
                child: Text(
                  "visible\ntrue",
                  style: TextStyle(fontSize: 20),
                ),
              )),
          box,
        ],
      ),
    );
  }
}