如何在 widget 属性中编写 if 条件?

编程


我想在图标小部件中使用 if 条件,但 Dart 给出错误。 应该如何正确使用呢? 谢谢。

class Cell extends StatelessWidget {
  const Cell({super.key, this.caseTrend = false});

  final bool caseTrend;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          const Text("23.410"),
          Icon(
          if(caseTrend) { //<== getting error here: Expected an identifier.dart Expected to find ')'.
            Icons.trending_up,
            color: Colors.green,
          } 
          else
          {
            Icons.trending_down,
            color: Colors.red,
          },
            size: 24, 
          )
        ],
      ),
    );
  }
}

我尝试过的:

class Cell extends StatelessWidget {
  const Cell({super.key, this.caseTrend = false});

  final bool caseTrend;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          const Text("23.410"),
          Icon( //This way working well but using conditions two times
           caseTrend ? Icons.trending_up : Icons.trending_down, 
           color: caseTrend ? Colors.green : Colors.red,
            size: 24, 
          )
        ],
      ),
    );
  }
}

解决方案1

不幸的是,您无法像在方法或函数中编写一样直接在小部件属性中编写 if 语句。 但是,您可以通过几种方法在小部件中编写条件语句。 您可以使用三元运算符 (condition ? expr1 : expr2) 在 widget 属性内实现条件渲染,正如您提到的您所尝试的那样。 以下是使用一些其他替代解决方案来使用内部小部件属性的参考链接。
Flutter if else:您需要了解的 3 种主要方法(代码) [January 2024] – FlutterBeads[^]

コメント

タイトルとURLをコピーしました