Flutter Dart: return value for a class

Asked

Viewed 63 times

-1

When calling the method callReadTotal(), the global variable tot receives the value and it prints without problems its result within it. However, in the class ThemesList called it, the variable receives null.

Could someone tell me what’s missing there? Thanks in advance.

callReadTotal() async {
  await firestoreInstance.collection("causas").get().then((value) {
    tot = value.docs.length;   
  });
  print(tot);   
}
int tot;
FirebaseFirestore firestoreInstance = FirebaseFirestore.instance;
class ThemesList extends StatelessWidget {
  List<FlatButton> _getButtonBar(context) {
    callReadTotal(); //chamando o método
    print(tot); //recebe sempre null.
     .
     .
     . 

1 answer

0

You are not working correctly with asynchronous codes in Dart.

The asynchronous function callReadTotal() returns a Future<void>:

Future<void> callReadTotal() async {
  await firestoreInstance.collection("causas").get().then((value) {
    tot = value.docs.length;   
  });
  print(tot);   
}

Consequently _getButtonBar() also becomes asynchronous and must wait await the execution of callReadTotal().

Future<List<FlatButton>> _getButtonBar(context) async {
    await callReadTotal();
    print(tot);
}

This solves your problem. However, you should not work like this with global variables. Return this tot in function callReadTotal():

Future<int> callReadTotal() async {
  return await firestoreInstance.collection("causas").get().then((value) {
    tot = value.docs.length;   
  });  
}

Future<List<FlatButton>> _getButtonBar(context) async {
    int tot = await callReadTotal();
    print(tot);
}

I recommend reading the operation of asynchronous programming.

Browser other questions tagged

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