UI with CircularProgressIndicator, Provider and ternary operators, Flutter

Viewed 22

I'm having an issue where one of my widget is shown until it completes the ternary operator. I want to show a CircularProgressIndicator() or any loader while the ternary operator check which is the correct solution and display the Widget. But while the indicator is running, it switches to Widget1(), then the ternary operator check the values and returns the second one. What I want to do is show the loader until the ternary operator says, OK I checked, you need to display Widget2() and displays it, but now it first shows Widget1(), then the ternary operator checks if the conditions are met for the Widget2() to be displayed, it then switches to that one. I don't want to show the user that one screen in the middle of the process, it's quite confusing. I tried using FutureBuilder() but the data is already in the state, so I don't wanna call the API again, hence the problem. Here is the code below with comments:

Main screen where the action occurs:

class MainScreen extends StatefulWidget {

  @override
  _MainScreenState createState() => _MainScreen State();
}

class _MainScreenState extends State<MainScreen> {
@override
  Widget build(BuildContext context) {
/// all the data from the provider state, so I don't call the api again
    final vehicleStore = Provider.of<VehicleDataModel>(context, listen: true);
    final vehicleData = vehicleStore.vehicleListLength != 0
        ? vehicleStore.getVehicleByIndex(0)
        : null;
    final user = Provider.of<LoggedUserStore>(context, listen: true);
    final userData = user.getUserByGnetId(
        Provider.of<LoggedUserStore>(context, listen: false)
            .userEmail
            .toString());
    final tenant = Provider.of<LoggedTenantStore>(context, listen: true);
    final tenantData = tenant.getTenantInfoByTenantId(
        Provider.of<LoggedTenantStore>(context, listen: false)
            .tenantId
            .toString());
/// I first check if there is data for name and surname, show the progressindicator, then another ternary operator to see which widget to display, Widget1 or Widget2
    return (userData?.name == null ||
            userData?.surname == null ||
            tenantData?.firstName == null ||
            tenantData?.lastName == null)
        ?  Center(child: CircularProgressIndicator())
        : (userData?.addressCity == null ||
                tenantData?.addressCity == null ||
                vehicleData?.licencePlate == null)
            ? Widget1()
            : Widget2();
  }
}

Like I said, the best solution would be to show the CircularProgressIndicator until the second ternary operator does his thing, but I'm not sure what is the best approach.

Thanks in advance for the help!

0 Answers
Related