簡體   English   中英

Flutter:根據情況對文字使用不同的colors

[英]Flutter: Use different colors on text according to the situation

我有一個應用程序從 api 接收訂單數據並將它們顯示在列表視圖上。 有 4 種狀態(確定、等待、待處理和完成),我想用顏色顯示任何狀態,但我不知道該怎么做。

有任何想法嗎?

我的代碼:創建對象:

class Hist {
  final String codPedido;
  final String status;
  final String statusDescricao;
  final String usuario;
  final String placa;
  final String box;
  final String tipoVeiculo;
  final String dtCadastro;
  final String hrCadastro;

  Hist(
      {this.codPedido,
      this.status,
      this.statusDescricao,
      this.usuario,
      this.placa,
      this.box,
      this.tipoVeiculo,
      this.dtCadastro,
      this.hrCadastro});

  factory Hist.fromJson(Map<String, dynamic> json) {
    return Hist(
        codPedido: json['cod_pedido'],
        status: json['status'],
        statusDescricao: json['status_descricao'],
        usuario: json['usuario'],
        placa: json['placa'],
        box: json['box'],
        tipoVeiculo: json['tipo_veiculo'],
        dtCadastro: json['dt_cadastro'],
        hrCadastro: json['hr_cadastro']);
  }
}

建設者:

  Widget build(BuildContext context) {
    return FutureBuilder<List<Hist>>(
      future: _fetchHist(context),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<Hist> data = snapshot.data;
          return _histListView(data);
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
        return Center(
          child: Container(
            height: 100,
            width: 100,
            margin: EdgeInsets.all(5),
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              valueColor: AlwaysStoppedAnimation(Colors.green),
            ),
          ),
        );
      },
    );
  }

獲取部分:

  Future<List<Hist>> _fetchHist(BuildContext context) async {
    //Classe para carregar os pedidos da api
    //
    final prefs = await SharedPreferences.getInstance(); //pega o usuário logado
    final key = 'usuario';
    final value = prefs.getString(key);
    print('saved tester $value');
    String usu = value; //fim

    //Carrega os itens da api
    Response response = await Dio().post(
        server,
        data: {"usuario": usu});

    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.data);
      print(response.data);
      return jsonResponse.map((job) => new Hist.fromJson(job)).toList();
    } else {
      throw Exception('Falha ao carregar histórico');
    }
  }

listview 和 tile 部分:


  ListView _histListView(data) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return _tile(
              data[index].codPedido + " - " + data[index].hrCadastro,
              "Status: " +
                  data[index].statusDescricao +
                  "\nBox: " +
                  data[index].box +
                  " " +
                  data[index].tipoVeiculo +
                  " " +
                  data[index].placa,
              Icons.settings,
              context,
              index);
        });
  }

  ListTile _tile(String title, String subtitle, IconData icon,
          BuildContext context, int counter) =>
      ListTile(
        title: Text(title,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 20,
            )),
        subtitle: Text(subtitle),
        leading: Icon(
          icon,
          color: Colors.green[500],
        ),
        onTap: () {
          _fetchPed(title);
          for (int i = 0; i < dataHolder.length; i++) {
            pedList.add(Ped.fromJson(dataHolder[0]));
          }

如果我理解你,你想為文本實現不同的顏色。 您可以創建 function 來檢查狀態並根據它傳遞顏色

         Color checkStatus(String st){
         Color a;
          if(st=="OK") 
           a=Colors.red;
         else if
           .... other statuses

在你的文本中你會得到這樣的:

       Text("my status", color: checkStatus("OK"))

為什么不在 class 中創建一個顏色字段,然后在創建 class 時像這樣初始化顏色。

class Hist {
  String status;
  Color color;

  Hist({this.status}) {
    _intialize();
  }

  _intialize() {
    if (status == 'Ok') {
      color = Colors.pink;
    } else if (status == 'waiting') {
      color = Colors.orange;
    }
    //Rest of your conditions 
  }
}

//Then you would use it like this
Hist hist = Hist(status: 'waiting');


Container(
          height: 100,
          width: 100,
          color: hist.color,
        ),

我在容器上使用顏色屬性,但顯然你可以在任何地方使用它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM