Picking up new information from a website and adding a new line with this information every time it is updated

Asked

Viewed 37 times

-1

hello guys I’m trying to get data from a site api(own server) and so show the new data in the application as soon as the site makes an update with new information, thus adding a new line and keeping the data old, I tried to use the listview, but I couldn’t because only the new line appears and the others disappear.

if (snapshot.data != null && snapshot.data != oldSnapshot) {
                        oldSnapshot = snapshot.data;
                        return ListView.separated(itemBuilder: (_, index) => Text('Volta :' +
                              snapshot.data.lap.toString() +
                              ' Velocidade :' +
                              snapshot.data.vel.toString() +
                              ' Tempo :' +
                              snapshot.data.datetime.toString()),
                               separatorBuilder: (_, int i) => Divider(), 
                               itemCount: 28,
                               controller: controller,
                          );
  • Show more of your code, just with this part we can’t help you in much... How are you getting the data from the API? Does the API use Socketio or something so you can listen to changes in real time? Your API returns record by record or all at once? Edita your question and give us more information expensive.

1 answer

0

From what I see in your code you’re updating the ListView with the amount you just received, by the way you put the code I assume you’re using the StreamBuilder which will rebuild your list each time you receive a new server line. There is no method for adding lines to a ListView, every time the update value will show the current value of your list and will not keep any reference to old values, possible solutions to your problem:

  1. Use a Statefulwidget

This would be your method build:

Widget build(BuildContext context) {
    /// Evite fazer operações complexas dentro do metodo build, visto que o mesmo pode e será chamado
    /// várias vezes enquanto a sua página estiver aberta, e em cada chamada toda a sua 
    /// lógica será reprocessada
    return ListView.separated(
      itemBuilder: (_, index) => lista[index],
      separatorBuilder: (_, int i) => Divider(), 
      itemCount: 28,
      controller: controller,
    );
  }

As you can notice the method build simply create and display the list, the necessary logic you can set in to the method initState

List<String> lista = List();
StreamSubscription<String> subscription;

@override
initState(){
  /// Suponho que de qualquer forma o seu script que recebe tais informações
  /// do server tenha uma stream onde ele emite os valores recebidos pelo server
  myServerAPI.listen((data) {
    /// Dê preferência por ultilizar a interpolação, é mais legível
    final line = 'Volta: ${data.lap.toString()} Velocidade ${data.vel.toString()} Tempo: ${data.datetime.toString()}';

    /// Atualize o state do seu Widget
    setState(() {
      /// Adicione a nova linha a sua lista
      lista.add(line);
    });
  })
}

Don’t forget to cancel the subscription since it is no longer necessary, you can do this when your Widget will be destroyed for example:

@override
dispose(){
  subscription.cancel();
  super.dispose();
}
  • Tip: Your answer may be correct in his case, but don’t try to use your crystal ball always, if you’re not going to keep popping questions ever shallower and without necessary information...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.