【问题标题】:How to conditionally render in Flutter如何在 Flutter 中进行条件渲染
【发布时间】:2021-06-13 08:43:03
【问题描述】:

我有一个钱包圈,它可以响应已完成的付款。我的问题是当钱包金额为零时,我希望绘制圆圈的小部件不可见。

我现在所做的是,我使用三元运算符在 Custompaint Widget 中检查它。我错过了什么?

 CustomPaint(
                    painter: (this.total <= 0)
                        ? CurvePainter(colors: [
                            // To test if the color changes
                            Colors.red.withOpacity(0.9),
                            Colors.red.withOpacity(0.9)
                          ], angle: 0, strokeWidth: 0)
                        : CurvePainter(
                            colors: [
                              Colors.white.withOpacity(0.9),
                              Colors.white.withOpacity(0.9),
                            ],
                            angle: 360 - ((this.used / this.total) * 360),
                            strokeWidth: this.strokeWidth,
                          ),
                    size: Size.fromRadius(strokeWidth),
                    child: SizedBox(
                      width: this.radius,
                      height: this.radius,
                    ),
                  

)

【问题讨论】:

    标签: flutter conditional-statements flutter-widget


    【解决方案1】:

    如果你想有条件地绘制小部件,你可以像这样使用三元运算符:

        (this.total <= 0)
           ? CustomPaint(
                painter:CurvePainter(
                        colors: [
                          Colors.white.withOpacity(0.9),
                          Colors.white.withOpacity(0.9),
                                ],
                        angle: 360 - ((this.used / this.total) * 360),
                        strokeWidth: this.strokeWidth,
                              ),
                size: Size.fromRadius(strokeWidth),
                child: SizedBox(
                          width: this.radius,
                          height: this.radius,
                        ),
            ) : Container(), // <--- Use it here, not inside CustomPainter
    

    【讨论】:

    • 我的目标是根据条件绘制Custompaint的位置参数Curvepainter。它应该只影响 Curvepainter.. 当 this.total 为零时,不应绘制曲线画家
    • 当没有参数的 Container() 到达小部件树时,它不会产生任何影响。另一方面,当您传递给画家零宽度时,它仍会渲染,并且在大多数情况下以最小宽度绘制。
    • 另一种方法是将条件值传递给画家类并创建将根据其状态执行的函数。当您的画家包含多个绘制函数并且您希望它们分别渲染时,它更复杂但很好的解决方案。
    【解决方案2】:

    你会改变 setState 里面的变量吗?

    setState((){
     total = 0;
    });
    

    setstate 重新渲染屏幕。

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2022-07-05
      • 2020-09-20
      • 1970-01-01
      • 2021-07-18
      • 2019-04-04
      • 2011-03-15
      • 2019-09-06
      • 2019-08-18
      相关资源
      最近更新 更多