【发布时间】:2021-05-05 19:20:11
【问题描述】:
我的颤振应用程序中有一个类别栏。最初所有类别名称都是硬编码的,但现在我从 json 数据中获取类别名称。
我需要做的是为所选按钮设置绿色容器颜色,文本将为白色。其他按钮将是黑色文本+白色容器。
当我有硬编码数据时,我像这样单独检查按钮的索引:
对于容器:
color: buttonIndex == 0 ? Color(0xff75c760) : Colors.white,
按钮文本:
buttonIndex == 0 ? Colors.white : Colors.black,
但现在可以有任意数量的类别名称,我不知道如何将其变成动态名称。
完整代码:
class _RecipeCategoryBarState extends State<RecipeCategoryBar> {
late AppData appData;
int buttonIndex = 0;
void setIndex(int val) {
setState(() {
buttonIndex = val;
});
}
Widget recipeCategoryButton() {
return Container();
}
@override
void initState() {
super.initState();
appData = Store.instance.getAppData();
}
@override
Widget build(BuildContext context) {
return Container(
height: 50.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: appData.recipeCategories!.length,
itemBuilder: (BuildContext context, int index) {
return ButtonBar(
children: <Widget>[
Material(
color: buttonIndex == 0 ? Color(0xff75c760) : Colors.white,
borderRadius: BorderRadius.circular(15),
clipBehavior: Clip.antiAlias,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 5,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextButton(
onPressed: () {
setIndex(0);
widget.sendDataToParent(index);
},
child: Text(
appData.recipeCategories![index].categoryName!,
style: TextStyle(
color:
buttonIndex == 0 ? Colors.white : Colors.black,
fontSize: 12,
fontFamily: "Poppins",
fontWeight: FontWeight.w500,
),
),
),
],
),
),
),
],
);
},
),
);
}
}
【问题讨论】:
-
颜色以什么格式传递?
-
对不起,我不明白你所说的“什么格式”是什么意思
-
6 位十六进制颜色代码是一种可能的颜色格式。
-
哦,我明白了。我用的是
Color(0xff75c760)这种格式