flutter 中的Future方法读取踩的小坑

2020-04-26  本文已影响0人  天渺工作室

flutter dart 语法中 Future其实和js中的Promse 原理是一样的 Future 声明的函数都是异步函数

void testThen1() {
  Future f1 = new Future(() => null);
  Future f2 = new Future(() => null);
  Future f3 = new Future(() => null);

  f1.then((_) => print("f1 -> f1"));
  // f2 then 异步回调里面还有异步回调
  f2.then((_) {
    print("f2 -> f2");
    f1.then((_) => print("f2.then -> f1"));
  });
  f3.then((_) => print("f3 -> f3"));
}

//打印结果
f1 -> f1
f2 -> f2
f2.then -> f1
f3 -> f3
image.gif

当遇到Future声明的函数时候 想要获取其return 返回值 必须也用异步的方法 否则只能读取外层的Future

Future<bool> demo() async{
    await return true;
}

//用异步的方法读取
demoRead() async{
 await demo();//打印true
}

//或者用then 的方法去接受 获取
demo.then((e) {
    print("e");

  });
image.gif

dart 的语法还是多看看官方的解释

上一篇 下一篇

猜你喜欢

热点阅读