我有一个定制的BottomNav栏,并成功地根据选定的索引更改了背景 colored颜色 .我通过一个三元声明来做到这一点:

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);},

这可能只是一个简单的语法问题--我还是个初学者.

推荐答案

您可以定义如下函数:

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),

Flutter相关问答推荐

自动测试Flutter应用程序进行QA的最佳方法是什么?

使用Flutter 提供程序包加载状态应用程序时,在自定义按钮中显示CircularProgressIndicator

手势捕获的异常:类型';Double';不是类型转换中类型';Double';的子类型

video_player在Android上返回401 Unauthorized with Bunny CDN

如何在默认情况下隐藏appBar并在向下滚动时显示它- Flutter

我有一个问题:类型';()=>;Null';不是类型转换中类型';(Int)=>;void';的子类型

在setState之后,Ffltter ListView.Builder未更新

轻松本地化包翻译在底部导航栏项目标签Flutter 翼dart 中不起作用

构建上下文不能跨异步间隙使用

没有为类型 'Widget' 定义运算符 '[]' .try 定义运算符[]

如何在 Flutter (iOS) 中解决这个问题

flutter 在文本字段中更改部分文本选定 colored颜色

如何在 Flutter 执行通知时运行后台代码?

无法在 flutter 中更新 void 方法内的变量值

如何修复int类型不是String类型的子类型

Flutter:如何判断嵌套列表是否包含值

为什么容器会填满整个空间?

Flutter 中父容器顶部的 Gridview 间距额外区域

Flutter Firestore 数据库排序最近 24 小时内最喜欢的文档

设计响应式卡片的最佳方法,以避免像素溢出错误或 _AssertionError