【问题标题】:Change colour of widget depending on index/variable根据索引/变量更改小部件的颜色
【发布时间】:2022-10-12 22:52:56
【问题描述】:

我有一个自定义的底部导航栏,并根据 selectedIndex 成功更改了背景颜色。我通过三元语句来做到这一点:

backgroundColor: selectedIndex == 0
      ? const Color.fromARGB(255, 0, 52, 35)
      : const Color.fromARGB(255, 0, 13, 52),

现在我添加了第三个屏幕,我想按照以下几行设置一个 if 语句:

backgroundColor: 
      if (selectedIndex == 0)
      {const Color.fromARGB(255, 0, 52, 35);}
      if (selectedIndex == 1)
      {const Color.fromARGB(255, 0, 13, 52);}
      if (selectedIndex == 2)
      {const Color.fromARGB(255, 87, 0, 54);},

这可能只是一个简单的语法问题——我是 Flutter 的新手。

【问题讨论】:

    标签: flutter dart if-statement


    【解决方案1】:

    您可以使用switch 创建一个单独的方法。

    Color getColor(int selectedIndex) {
      switch (selectedIndex) {
        case 0:
          return const Color.fromARGB(255, 0, 52, 35);
    
        case 1:
          return const Color.fromARGB(255, 0, 13, 52);
    
        case 2:
          return const Color.fromARGB(255, 87, 0, 54);
    
        default:
          return Colors.green;
      }
    }
    

    并使用

    backgroundColor: getColor(selectedIndex),
    

    更多关于switch-and-case

    【讨论】:

      【解决方案2】:

      你可以像这样定义一个函数:

      Color getBackgroundColor(int selectedIndex){
         if (selectedIndex == 0){
            return const Color.fromARGB(255, 0, 52, 35);
         }else if (selectedIndex == 1){
            return const Color.fromARGB(255, 0, 13, 52);
         }else {
            return const Color.fromARGB(255, 87, 0, 54);
         }
      }
      

      并像这样使用它:

      backgroundColor: getBackgroundColor(selectedIndex),
      

      【讨论】:

        【解决方案3】:

        你实际上可以嵌套三元表达式来得到你想要的,比如:

        backgroundColor: selectedIndex == 0
          ? const Color.fromARGB(255, 0, 52, 35)
          : selectedIndex == 1
            ? const Color.fromARGB(255, 0, 13, 52)
            : const Color.fromARGB(255, 87, 0, 54),
        

        尽管我会更多地推荐 Yeasin Sheikh 的答案,尤其是如果您想添加更多索引

        【讨论】:

        • 有趣的!谢谢伊沃
        【解决方案4】:

        实现此目的的另一种方法是使用Map<int, Color> 并将索引用作地图的key

        Color getColor(int selectedIndex) {
          return const <int, Color>{
                0: Color.fromARGB(255, 0, 52, 35),
                1: Color.fromARGB(255, 0, 13, 52),
                2: Color.fromARGB(255, 87, 0, 54),
              }[selectedIndex] ?? Colors.green; // default value
        }
        

        【讨论】:

          猜你喜欢
          • 2015-05-28
          • 1970-01-01
          • 2021-02-07
          • 2022-01-02
          • 2021-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多