-2

Estou tendo problemas para atualizar o status Estou pegando uma lista e mostrando ela se eu Coloco o SetState em _getProdPromo fica em loop, se eu não coloco, os dados não são atualizados na tela, alguem sabe como eu posso chamar corretamente

import 'package:gestoque/ConsultaPromocao.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:gestoque/Api.dart';

class ViewProdutosPromocionais extends StatefulWidget {
  @override
  _ViewProdutosPromocionaisState createState() =>
      _ViewProdutosPromocionaisState();
}



class _ViewProdutosPromocionaisState extends State<ViewProdutosPromocionais> {

  var promocoes = new List<ConsultaPromocao>();
  String _search;

  Future<List> _getPromocoes() async {

    Api.getProdPromo().then((response) {

      List lista = json.decode(response.body);
      promocoes =
          lista.map((model) => ConsultaPromocao.fromJson(model)).toList();
    });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Image.asset("assets/logo_topo_1.png"),
          backgroundColor: Colors.orange,
        ),
        backgroundColor: Colors.white,
        body: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(10.0),
              child: TextField(
                decoration: InputDecoration(
                    labelText: "Nome do Produto",
                    labelStyle: TextStyle(color: Colors.black),
                    border: OutlineInputBorder()),
                style: TextStyle(color: Colors.black, fontSize: 18.0),
                textAlign: TextAlign.center,
              ),
            ),
            Expanded(
              child: FutureBuilder(
                future: _getPromocoes(),
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.waiting:
                    case ConnectionState.none:
                      return Container(
                        width: 200.0,
                        height: 200.0,
                        alignment: Alignment.center,
                        child: CircularProgressIndicator(
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.orange),
                          strokeWidth: 5,
                        ),
                      );

                    default:
                      if (snapshot.hasError)
                        return Container();
                      else
                        return ListaProdutosPromocionais();
                  }
                },
              ),
            )
          ],
        ));
  }



  ListaProdutosPromocionais() {
    return ListView.builder(
        itemCount: promocoes.length,
        itemBuilder: (context, index) {
          return Container(
              child: Card(
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Text('Código: : ',
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold)),
                    Text(promocoes[index].codprod),
                  ],
                ),
                Row(
                  children: <Widget>[
                    Text('Nome: ',
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold)),
                    Text(promocoes[index].descrprod),
                  ],
                ),
                Row(
                  children: <Widget>[
                    Text('Valor R\$ ',
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold)),
                    Text(promocoes[index].vlrvenda),
                  ],
                ),
              ],
            ),
          ));
        });
  }
}


1

3 Respostas 3

1

Coloca num timer para fazer frequentemente, para iniciar coloca no iniState

void initState() {
    super.initState();
     Timer(Duration(seconds: 60), () => setState((){});
}
1

Consegui resolver, da seguinte forma...

inseri uma var para o retorno

    var data =  await Api.getProdPromo().then((response) {
      List lista = json.decode(response.body);
      promocoes =
          lista.map((model) => ConsultaPromocao.fromJson(model)).toList();
    });
  }

depois eu chamei a função no construtor..

_ViewProdutosPromocionaisState(){
    _getPromocoes();
  }````

1

Como você está fazendo uso de um FutureBuilder você não precisa de setState ou workarounds, basta modificar teu metodo da seguinte forma:

  Future<List> _getPromocoes() async {

    var response await Api.getProdPromo();

    List lista = json.decode(response.body);
    promocoes = lista.map((model) => ConsultaPromocao.fromJson(model)).toList();

    return promocoes;
  }

Você está tendo problemas com funções async (Assíncronas), aconselho dar uma estudada melhor sobre...

Da forma que esta fazendo, fica até sem sentido o uso do FutureBuilder.

1
  • entendi....Vlw vou ler mais sobre o Assunto , vlw
    – Juliano
    14/03/2020 às 12:34

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .