Flutter:根据情况在文本上使用不同的颜色

问题描述 投票:0回答:2

我有一个应用程序可以从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 _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]));
          }
android flutter
2个回答
0
投票

如果我了解您,则希望为文本提供不同的颜色。您可以创建检查状态并根据其传递颜色的功能

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

并且在您的文本中,您将像这样:

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

0
投票

为什么不在类中创建颜色字段,然后在创建类时却像这样初始化颜色。

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,
        ),

我正在容器上使用color属性,但显然您可以在任何地方使用它

© www.soinside.com 2019 - 2024. All rights reserved.