I am doing this example tutorial on async functions and reviewing this section
import 'dart:io';
class ProceessedData {
ProceessedData(this.data);
final String data;
Future<String> empty() {
return Future.delayed(const Duration(seconds: 4),
() => HttpException('http://www.google.com.').toString());
}
}
void main(List<String> args) {
Future<String> _loadFromDisk() {
return Future.delayed(const Duration(seconds: 4), () => 'Lectura de disco');
}
Future<String> _fetchNetworkData(String codigo) {
return Future.delayed(
const Duration(seconds: 4), () => 'lectura de red codigo $codigo');
}
Future<ProceessedData> createData() async {
try {
final id = await _loadFromDisk();
final data = await _fetchNetworkData('4');
return ProceessedData(data);
} on HttpException catch (err) {
print('Network error: $err');
return ProceessedData.empty();
} finally {
print('All done!');
}
}
}
I see that in the exception ProceessedData.empty()
which I must define in my main class since it does not exist but I thought it should be defined in the following way
Future<String> empty() {
return Future.delayed(const Duration(seconds: 4),
() => HttpException('http://www.google.com.').toString());
}
but when validating, this error is still indicated
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)
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("");
}