【发布时间】:2020-11-13 05:15:52
【问题描述】:
我正在构建一个颤振应用程序。有注册窗口,当用户输入手机号码时,它会检查它是否已经注册。但问题是该函数没有等待来自firebase的结果。如果用户不存在,则函数返回true为false。 但是这里没有返回值
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zshoperretail/otp_verification.dart';
class mobilewindow extends StatelessWidget {
TextEditingController mobileController=new TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Center(
child:Column(
mainAxisAlignment: MainAxisAlignment.center,
children:[
ClipRRect(
borderRadius: BorderRadius.circular(5),
child:Container(
height: 50,
width: 300,
color: Colors.white,
child:TextField(
maxLength: 10,
maxLengthEnforced: true,
controller: mobileController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: InputBorder.none,
hintText:"Mobile Number",
hintStyle: TextStyle(color: Colors.red),
),
),),),
SizedBox(height: 5,),
ElevatedButton(
child: Text("Next",style: TextStyle(color: Colors.white),),
onPressed:() =>saveMobile(context),
)
])
),
);
}
saveMobile(BuildContext context) async{
var mobile= mobileController.text;
mobile="+91"+mobile;
var result1='';
result1=await checkMobile(mobile);
print('check1'+result1);
if(result1=='false') {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('mobile', mobile);
Navigator.push(
context, MaterialPageRoute(builder: (context) => otp_verification()));
}
else{
print(result1);
showDialog(
context: context,
builder: (BuildContext context){
return AlertDialog(
title: Text("Error"),
content: Text("Account already registered.please login."),
actions: [
FlatButton(
child: Text("Close"),
onPressed: (){
Navigator.of(context).pop();
},
)
],
);
}
);
}
}
Future<String>checkMobile(String mobile) async{
FirebaseFirestore firestore= FirebaseFirestore.instance;
var result="";
firestore.collection('retail_users').doc(mobile).get().then((DocumentSnapshot snapshot)async{
if(snapshot.exists){
print("hello");
result='true';
}
else{
print("hellno");
result='false';
}
});
return(result);
}
}
【问题讨论】:
-
使用
FutureBuilder并为future参数提供检查手机号码是否已注册的未来功能,这将完成这项工作 -
Future builder 用于小部件对吧?
-
是的,将
body或Scaffold中定义的小部件包装在Future Builder 中 -
我不想将它包装在小部件中。我只想在函数中执行。
-
.... 等待 firestore.collection(....
标签: firebase function flutter dart async-await