Search code examples
dartdart-async

How to use dart future.sync method


When i try to use future.sync from class future like

import 'package:async/async.dart';
import 'dart:async';

void main() {
    var fur3 = new Future<int>(() => 45);
    int z = Future.sync(fur3);
    print(z);
}

i've got the error message

Breaking on exception: object of type NoSuchMethodError

Do i use future.sync in the wrong way?

My second question is

import 'package:async/async.dart';

void main() {
  var fur1 = new Future<int>(() => 45);
    fur1.then((value) {
      return value;
    }).catchError((err) => print('catchError1: ${err}'));
}

why when i try to import async library from package, i've got compiler message

Breaking on exception: object of type TypeError
Undefined class 'Future'

what am i do here wrong?


Solution

    1. You don't pass a future into Future.sync() but a closure to be executed immediately.
    Future z = Future.sync(() => print('bla'));
    
    1. async is an internal package. You import it using

      import 'dart:async';

    Internal packages don't need to be added to pubspec.yaml dependencies because they are always available. The different import statement is related to that.