2
votes

I am not able to use a Future call in a constructor of my controller. I am trying to initialize a list from database on page load, which requires me to use Future.

The value is retrieved using a method declared in the service class, which i have added in the module class just before the controller.

type(DataStreamService);

type(DataStreamController);

Here is the code for my controller:

@NgController(selector: '[data-stream-controller]', publishAs: 'DataStreamCtrl')
class DataStreamController {
  List<InputDataStruct> dataStream;

  DataStreamController(DataStreamService dataStreamSrvc){

    Future<List<InputDataStruct>> getDataStreamFtr = dataStreamSrvc.getDataStream();
    getDataStreamFtr.then((value){
      dataStream = value;
    })
    .catchError(print("Error occured"));
  }
}

Is using Future in constructor not recommended. If not what am i missing here.

Here is the dataStreamSrvc.getDataStream() code:

Future<List<InputDataStruct>> getDataStream(){
    List<InputDataStruct> dataStream = [];
    Completer completer = new Completer();

    Future getSomeInfoFtr = myDbHelper.getSomeInfo();

    getSomeInfoFtr.then((infoAndList){
      for(String info in infoAndList){
    inputDataStruct = new InputDataStruct(info);
    dataStream.add(inputDataStruct);
      }
    });

    completer.complete(dataStream);

    return completer.future;
}
1
What do you mean by not working? I guess you just access dataStream before it actually got a value assigned. Where do you check if dataStream has a value? Try to add a print(value) in then to see if a value is returned. - Günter Zöchbauer
In the console i see: "The null object does not have a method 'then'. NoSuchMethodError : method not found: 'then' Receiver: null Arguments: [Closure: (dynamic) => dynamic]" - jsbisht
Then it seems that dataStreamSrvc.getDataStream() doesn't return a value. Maybe you forgot a return in getDataStream()? - Günter Zöchbauer
So, as you said the dataStream is null. How do i make sure the dataStreamSrvc is not null before i use it? - jsbisht
I am using completer.future to return the value from dataStreamSrvc.getDataStream() - jsbisht

1 Answers

0
votes

I have not actually tried the code but I think it should work. I have also simplified a bit. It is not necessary to store the future in a variable.

@NgController(selector: '[data-stream-controller]', publishAs: 'DataStreamCtrl')
class DataStreamController {
  List<InputDataStruct> dataStream;

  DataStreamController(DataStreamService dataStreamSrvc){
    dataStreamSrvc.getDataStream().then((value){
      dataStream = value;
    })
    .catchError(print("Error occured"));
  }
}

Future<List<InputDataStruct>> getDataStream(){
  List<InputDataStruct> dataStream = [];

  return myDbHelper.getSomeInfo().then((infoAndList){
    for(String info in infoAndList){
      inputDataStruct = new InputDataStruct(info);
      dataStream.add(inputDataStruct);
    }
    return dataStream;
  });
}