Flutter: Как раскрасить данные, отображаемые с JSON согласно декларации - PullRequest
0 голосов
/ 25 мая 2020

это 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
                                    )
                                  ]));
                            });

Ответы [ 3 ]

1 голос
/ 25 мая 2020

Попробуйте использовать карту следующим образом:

var colors = { "NA":Color(0xFFFF9E80), "EU":Color(0xFF2196F3) [,…..,key_n:value_n] }

, затем получите доступ, как это

colors["NA"];....colors["EU"];
0 голосов
/ 25 мая 2020

Чтобы избежать шаблона, вы можете создать свой метод расширения, например:

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;

Для сопоставления имен файлов ресурсов попробуйте следующий способ:

extension AssetsExtension on String {
  String get asset => this.toLowerCase().replaceAll(" ", "_");
}

main(){
  print("North America".asset); //north_america
  print("Europe".asset); //europe
}
0 голосов
/ 25 мая 2020

Оператор if и удаление конструкторов 'const' могут решить вашу проблему:

color: countries[index].continent == 'Europe' ? ContinentColor.EU : countries[index].continent == 'North America' ? ContinentColor.NA : ContinentColor.Asia,

или с помощью функции:

Color colorRule(String continent){
  if(continent == 'Europe'){
    return ContinentColor.EU;
  }
  else if(continent == 'North America'){
    return ContinentColor.NA;
  }
  else{
    return ContinentColor.Asia;
  }
}

//in your list view:
color: colorRule(countries[index].continent);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...