كيف يمكن كتابة الشرط في خاصية القطعة؟


أرغب في استخدام شرط 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 مباشرة داخل خصائص عنصر واجهة المستخدم الخاص بك كما لو كنت تكتب في طريقتك أو وظيفتك. ولكن هناك عدة طرق يمكنك من خلالها كتابة عبارة شرطية داخل عنصر واجهة المستخدم الخاص بك. يمكنك استخدام المعامل الثلاثي (الشرط؟ expr1 : expr2) لتحقيق العرض الشرطي داخل خاصية عنصر واجهة المستخدم، كما ذكرت ما قمت بتجربته. فيما يلي الرابط المرجعي لاستخدام بعض الحلول البديلة الأخرى لاستخدامها داخل خصائص عنصر واجهة المستخدم.
Flutter if else: أهم 3 طرق تحتاج إلى معرفتها (الكود) [January 2024] – خرز الرفرفة[^]

コメント

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