如何在 Flutter 中进行条件渲染

时间:2021-03-16 03:56:05

标签: flutter conditional-statements flutter-widget

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

我现在所做的是使用三元运算符在 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,
                    ),
                  

)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你是否更改了 setState 中的变量?

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

setstate 重新渲染屏幕。