gpt4 book ai didi

json - Flutter:如何根据声明为JSON显示的数据着色

转载 作者:行者123 更新时间:2023-12-03 04:47:40 24 4
gpt4 key购买 nike

这是json文件

[
{
"id": 1,
"country": "United States",
"continent": "North America"
},
{
"id": 2,
"country": "Germany",
"continent": "Europe"
},
{
"id": 3,
"country": "United Kingdom",
"continent": "Europe"
}
]

我要设置条件如下:

1.北美(美国)的国家/地区将使用
CotinentColor.NA 2.欧洲国家(德国和英国)
将使用CotinentColor.EU


那我该怎么办?

这是custom_color文件
import 'package:flutter/material.dart';

class ContinentColor {
static const Color NA = Color(0xFFFF9E80);
static const Color EU = Color(0xFF2196F3);
static const Color Asia = Color(0xFFE0E0E0);
}

这是主文件:

ListView.builder(
itemCount: countries.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: Column(children: <Widget>[
Text(
countries[index].country,
style: const TextStyle(
color:,
// How to apply color according follow the conditional
)
]));
});

最佳答案

为了避免样板,可以创建扩展方法,如下所示:

extension ContinentExtension on String {
Color get color{
switch (this.toUpperCase()) {
case "EUROPE":
return ContinentColor.EU;
case "NORTH AMERICA":
return ContinentColor.NA;
case "ASIA":
return ContinentColor.Asia;
default:
return Color(0xFFFFFFFF);
}
}
}

String americaCon = "North America";

print("Europe".color);
print(americaCon.color);

color: countries[index].continent.color;

对于 Assets 文件名映射,请尝试以下方式:
extension AssetsExtension on String {
String get asset => this.toLowerCase().replaceAll(" ", "_");
}

main(){
print("North America".asset); //north_america
print("Europe".asset); //europe
}

关于json - Flutter:如何根据声明为JSON显示的数据着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62004437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com