Flutter GetX variable changes but UI does not

Issue

I have two RxLists containing custom models:

var openDepartures = RxList<Departure>([]);
var finishedDepartures = RxList<Departure>([]);

I bind a stream to populate these RxLists with values from firebase. Since my Stream(which I am binding to the variables) changes according to the user’s choice, I bind the new stream to the same variable, but since that would result in two streams controlling one variable, I "reset" the variable before that:

openDepartures = RxList<Departure>();
finishedDepartures = RxList<Departure>();
....
openDepartures.bindStream(
  Database().getOpenDepartures(
    userController.userLocation.value,
  ),
);
finishedDepartures.bindStream(
  Database().getFinishedDepartures(
    userController.userLocation.value,
  ),
);

The problem is that the UI is not refreshing, but when I do not "reset" the variables, everything works fine. What’s weird as well is that the variable does get populated with the correct data. It is just not shown in the UI.

What I have tried to fix that:

  • update() method
  • Get.reloadAll()
  • call .refresh() on the variables
  • disposing and initializing the controller again

My question is now, how do I get the screen to refresh, or does anyone have an idea how to bind a new stream without "resetting" the old one and having multiple streams on one variable?

Solution

I finally solved my problem. The underlying problem was that I was binding multiple streams to one variable and therefore the variable was updated whenever one of the streams fired. The solution was the following:

  • Create an RxList of the variable:

final _openDepartureList = RxList<RxList<Departure>>();

  • Create a getter for the last element of that list:

RxList<Departure> get openDepartures => _openDepartureList.last;

  • Remove the old items:
if (_openDepartureList.length >= 2) {
  _openDepartureList.removeRange(0, _openDepartureList.length - 1);
}
  • Add an empty RxList to the List

_openDepartureList.add(RxList.empty());

  • Bind the stream to the last element of the List, hence the one just added

_openDepartureList.last.bindStream():

That was it! I now always have the right stream bound to the variable I want and do not have multiple streams controlling one variable.

Answered By – lrsvmb

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *