#firebase #flutter #firebase-authentication
#firebase #флаттер #firebase-аутентификация
Вопрос:
я начал изучать flutter неделю назад. я пытаюсь создать систему аутентификации с помощью пакета Firebase_Auth и застрял с этой ошибкой. цель состоит в том, чтобы использовать авторизацию телефона firebase и с помощью codeAutoRetrievalTimeout автоматически принимать код sms. вот мой код
LoginScreen.dart
import 'package:flutter/material.dart';
import 'package:michot_2/screens/HomeScreen.dart';
import 'package:firebase_auth/firebase_auth.dart';
class LoginScreen extends StatelessWidget {
final _phoneController = TextEditingController();
final _codeController = TextEditingController();
Future<bool> loginUser(String phone, BuildContext context) async{
FirebaseAuth _auth = FirebaseAuth.instance;
_auth.verifyPhoneNumber(
phoneNumber: phone,
timeout: Duration(seconds: 60),
verificationCompleted: (AuthCredential credential) async{
Navigator.of(context).pop();
UserCredential result = await _auth.signInWithCredential(credential);
User user = result.user;
if(user != null){
Navigator.push(context, MaterialPageRoute(
builder: (context) => HomeScreen(user: user,)
));
}else{
print("Error");
}
//This callback would gets called when verification is done automatically
},
verificationFailed: (FirebaseAuthException exception){
print(exception);
},
codeSent: (String verificationId, [int forceResendingToken]){
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: Text("Give the code?"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: _codeController,
),
],
),
actions: <Widget>[
FlatButton(
child: Text("Confirm"),
textColor: Colors.white,
color: Colors.blue,
onPressed: () async{
final code = _codeController.text.trim();
AuthCredential credential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: code);
UserCredential result = await _auth.signInWithCredential(credential);
User user = result.user;
if(user != null){
Navigator.push(context, MaterialPageRoute(
builder: (context) => HomeScreen(user: user,)
));
}else{
print("Error");
}
},
)
],
);
}
);
},
codeAutoRetrievalTimeout: null
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(32),
child: Form(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Login", style: TextStyle(color: Colors.lightBlue, fontSize: 36, fontWeight: FontWeight.w500),),
SizedBox(height: 16,),
TextFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8)),
borderSide: BorderSide(color: Colors.grey[200])
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8)),
borderSide: BorderSide(color: Colors.grey[300])
),
filled: true,
fillColor: Colors.grey[100],
hintText: "Mobile Number"
),
controller: _phoneController,
),
SizedBox(height: 16,),
Container(
width: double.infinity,
child: FlatButton(
child: Text("LOGIN"),
textColor: Colors.white,
padding: EdgeInsets.all(16),
onPressed: () {
final phone = _phoneController.text.trim();
loginUser(phone, context);
},
color: Colors.blue,
),
)
],
),
),
),
)
);
}
}
Рабочий стол.dart
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class HomeScreen extends StatelessWidget {
final User user;
HomeScreen({this.user});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("You are Logged in succesfully", style: TextStyle(color: Colors.lightBlue, fontSize: 32),),
SizedBox(height: 16,),
Text("${user.phoneNumber}", style: TextStyle(color: Colors.grey, ),),
],
),
),
);
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:michot_2/screens/LoginScreen.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Michot Service',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginScreen()
);
}
}
Комментарии:
1. В чем здесь путаница?
2. Необработанное исключение: [firebase_auth/неизвестно] Данная строка пуста или равна нулю
3. Это отдельная проблема. Пожалуйста, опубликуйте это как отдельный вопрос.
Ответ №1:
codeAutoRetrievalTimeout
это обратный вызов, вызываемый по завершении времени автоматического извлечения кода. Это не может быть null.
Если вы этого не хотите, установите для этого значение this.
codeAutoRetrievalTimeout: (String verificationId){}
Комментарии:
1. хорошо, я немного изменил
codeAutoRetrievalTimeout: (String verificationId){ verificationId = verificationId; print(verificationId); print("Timout"); }
теперь он говорит о необработанном исключении: [firebase_auth / неизвестно] Данная строка пуста или равна нулю2. @bestilahun Это отдельная проблема. Пожалуйста, опубликуйте это как отдельный вопрос.
3. @Bestilahun да, пожалуйста, опубликуйте это как отдельный вопрос.
4. я пытался, но вы можете публиковать только один раз каждые 90 минут.
5. Если этот ответ подходит для этого вопроса, тогда примите.