Flutter 从 Future<bool> 方法返回 bool 类型

the*_*imm 2 dart flutter google-cloud-firestore

这个问题与非常相似,但解释对我的用例并没有太大帮助。我有一个 Future 类型的方法,它返回一个 bool 执行对 cloud firestore 的查询,以检查用户输入的用户名是否已经存在。

static Future<bool> doesNameAlreadyExist(String value, String 
name) async{
final QuerySnapshot result = await Firestore.instance
  .collection('users')
  .where(value, isEqualTo: name)
  .limit(1)
  .getDocuments();
  final List<DocumentSnapshot> documents = result.documents;
 return  documents.length == 1;
Run Code Online (Sandbox Code Playgroud)

}

当我在这里调用该方法时,我收到此错误 在此处输入图片说明

有没有办法从 Future 获取返回类型的 bool

小智 8

从返回的返回类型doesNameAlreadyExist就是Future<bool>,太行doesNameAlreadyExist("userName", usernameController.value) == true,实际上是Future<bool> == bool。你需要等待,否则结果。

doesNameAlreadyExist("userName", usernameController.value).then(value => value == true)
Run Code Online (Sandbox Code Playgroud)

或者

(await doesNameAlreadyExist("userName", usernameController.value)) == true
Run Code Online (Sandbox Code Playgroud)

在此处阅读有关异步编程的更多信息:Dart Futures