这是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
}