0
I am using Dart/Flutter to develop an application and in it I have two Firebase Listeners methods, as shown below, and I would like to know how, in the constructor method, I trigger one of the methods only after the first one has already populated the necessary variables.
Class and its builder:
class ItineraryBloc extends ChangeNotifier {
ItineraryBloc() {
// aqui irão as chamadas dos métodos citados acima...
}
List<Localidade> _listLocales = [];
List<Veiculo> _listVehicles = [];
String _selectedLocaleId = '';
...
1st method:
// LISTENER DAS LOCALIDADES CADASTRADAS
Future<List<Localidade>> getListAllLocales() async {
_db.collection('localidades').orderBy('nome').snapshots().listen((snapshot) {
listLocales = snapshot.docs.map((e) => Localidade.fromDocument(e)).toList();
selectedLocaleId = listLocales.firstWhere((item) => item.sedeRegional == true).id;
notifyListeners();
});
return listLocales;
}
2° method:
// LISTENER DOS VEÍCULOS CADASTRADOS POR LOCALIDADES
Future<List<Veiculo>> getListAllVehiclesByLocale() async {
_db.collection('veiculos').where('idLocalidade', isEqualTo: selectedLocaleId).orderBy('placa').snapshots().listen((qSnap) {
if (qSnap.docs.isNotEmpty) {
listVehicles = qSnap.docs.map((v) => Veiculo.fromDocument(v)).toList();
selectedVehicle = listVehicles[0];
} else {
listVehicles = [];
}
notifyListeners();
});
return listVehicles;
}
}
The method getListAllVehiclesByLocale
depends on the variable selectedLocaleId
which is set in the method getListAllLocales
.
My idea is to call these two methods in the class builder to populate the lists and related variables so only then do I use them in a widget. However, the widget needs to display a loading/processing feedback of these list to then display them in their respective PagesView
and ListView.
Even implementing your suggestions, @Naslausky, the return is still incorrect (see image: http://prntscr.com/v2hwgd ). Because, return the empty variables when loaded the Class. Should be set, since prints occur after the "awaits" of the methods in question. I have not had success in this question.
– Milhomens
No. You putting the print After calling an asynchronous function that does not have the await, it will print without waiting for the functions to finish. Try putting the print inside the function
loadLocalesAndVehiclesLists
and you’ll see what I say. I suggest you take a look at codelabs that Linkei in the answer, to better understand this part, or ask another question here on the site.– Naslausky
@Milhomens here you can see a reply in Portuguese on the subject as well.
– Naslausky