Home > Blockchain >  How to define a function that returns an object of the same class?
How to define a function that returns an object of the same class?

Time:06-11

I am doing this example enter image description here

If it is clear to me, I am returning a future value of type string and that the function that I have created createData() indicates that it will return a ProcessedData but I do not know how I should define the empty() function so that it returns an instance of its same class (I feel like if you were looking to loop)

CodePudding user response:

The purpose of ProcessedData.empty() is to create a new instance of ProcessedData (not String) which has no data. The fact that it is called directly on the ProcessedData class, means that empty() is either a static method, a factory constructor, or a named constructor (any of those will do).

It also doesn't need to return a Future - There is no need to wait for anything to get an instance of empty data. The fact that createData is an async method means that any value returned from the method will already be wrapped in a Future, so you can just return a ProcessedData.

With all that in mind, you can define empty like this:

class ProcessedData {
  // ...

  factory ProcessedData.empty() => ProcessedData("");
}

CodePudding user response:

Yes, that's because you are returning a String when calling ProccessedData.empty()
you can change the method empty to be a named constructor then it will work properly your ProccessedData class:

class ProceessedData {
    ProceessedData(this.data);

    final String data;

    Future<String> empty() {
        return Future.delayed(const Duration(seconds: 4),
            () => HttpException('http://www.google.com.').toString());
    }
}

Change it to:

class ProceessedData {
    ProceessedData(this.data);

    final String data;

    ProceessedData.empty() :
        data = HttpException('http://www.google.com.').toString();
}

CodePudding user response:

I don't understand why you're adding Future.delayed in your Data class but the error is that you're trying to return a String to a ProceessedData

I would do sonething like this:

class ProceessedData {
  ProceessedData(this.data);

  final String data;

  factory ProceessedData.empty() {
    return ProcessedData('');
  }
}
  • Related