【解決方法】ウィジェットのプロパティに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)を使用して、ウィジェットプロパティ内で条件付きレンダリングを実現できます。 これは、ウィジェット プロパティ内で使用する他の代替解決策を使用するための参照リンクです。
Flutter if else: 知っておくべきトップ 3 の方法 (コード) [January 2024] – フラッタービーズ[^]

コメント

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