Charly
Charly

Reputation: 79

Dart needs to expose functions callbacks in Futures?

I got a strong background in C# and Javascript and there is nothing I am not getting on Dart with Futures : Say I got a Future like this :

scoreFile.exists().then((r) => {
      if (r){
        List<ScoreRow> previousScores = await scoreFile.readAsString();
        scores = jsonDecode(previousScores);
      }
    });

I know this is not allowed because I need to make my callback a foo() function. But why clutter the space with a code to be used only in this place ? I mean, I really need to create as many little functions as I have callbacks ? I wouldn't do so with really complex processing, (which would be untestable if not put in a proper function) but for such a simple process ? Or maybe Dart design is "there is no such thing as simple code not to be tested" Because from a syntaxical point of view, my function already exists, she is just anonymous : she is stored in braces :) Thank you for your insight :)

Upvotes: 0

Views: 31

Answers (1)

lrn
lrn

Reputation: 71828

I'm not entirely sure what the problem is here.

Your code mixes async and non-async code, which is usually something to avoid unless absolutely necessary (which it rarely is).

You could perhaps write the code as:

if (await scoreFile.exists()) {
  scores = jsonDecode(await scoreFile.readAsString());
}

or you could continue doing what you are doing (fixing syntax and type issues):

scoreFile.exists().then((r) async {
  if (r) {
    var previousScores = await scoreFile.readAsString();
    return jsonDecode(previousScores);
  }
}).then((scores) {
  // use the scores variable.
});

If you use the then approach, then yes, you will have to make a lot of little callbacks because that's how it works. If you use the async/await syntax, those callbacks will be made for you.

Upvotes: 1

Related Questions