Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can non-trivial constructors call Future returning functions (how or alternatives)

Tags:

dart

Suppose you have:

class Schema {
    Schema.fromText(String jsonString) {
      ...
    }
}

In this constructor, assume there is an URL provided in the jsonString to download data and the only API to read an URL is one that returns a Future. Also, assume Schema is only a valid object when that URL data has been read and processed. Is it possible to even implement ...?

like image 254
user1338952 Avatar asked Aug 26 '13 12:08

user1338952


1 Answers

What you want to do is not possible with standard constructors.

Instead, try a static method that returns a new instance wrapped in a Future.

Something like:

class Schema {
  Schema._fromApi(String apiResults) { ... }
  static Future<Schema> build(String jsonString) {
    return getContentsOfUrl(jsonString['url'])
        .then((contents) => new Schema._fromApi(contents));
  }
}
like image 173
Seth Ladd Avatar answered Oct 01 '22 10:10

Seth Ladd