无法在保持 StreamProvider 的同时将 Flutter Firebase_Auth 从版本 0.15 更新到 0.18
Can't update Flutter Firebase_Auth from version 0.15 to 0.18 while keeping the StreamProvider
我有一个运行良好的大型 Flutter
应用程序...
现在,我正在努力更新具有重大更改的 Firebase firebase_auth: ^0.15.5+3
插件(自 2020 年夏季以来)。
当我在应用程序的多个位置检查 MyUser
时,我绝对需要保留我的 StreamProvider
。
我重新创建了一个最小的工作应用程序来专注于我的特定问题。
你能建议我应该如何调整这些:
1- getCurrentUser
in AuthService
: 看来我需要使用 authStateChanges
但不知道如何使用。
2- StreamProvider
in MyApp
:如何调整它以便我可以在我的应用程序中继续使用它而无需更改任何内容。
3- 使用这种方式:final currentUser = Provider.of<MyUser>(context)
然后 currentUser.uid
获取 uid 字符串。
请具体举例说明。
这是我的 puspec.yaml
name: myApp
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# **** FIREBASE ****
firebase_auth: ^0.15.5+3
provider: ^4.0.5
#firebase_core: "^0.5.2"
#firebase_auth: "^0.18.3"
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
这里是之前 Firebase
版本 0.15
的所有(工作)代码
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() {
runApp(MyApp());
}
//******************************************
class MyApp extends StatelessWidget {
@override Widget build(BuildContext context) {
//The following StreamProvider is what I am trying to recreate with new Firebase version.
return StreamProvider<MyUser>.value(
value: AuthService().getCurrentUser,
child: MaterialApp( title: 'MyApp',
home: Wrapper(),),);}
}
//******************************************
class Wrapper extends StatelessWidget {
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
// return either the Home or Authenticate widget
if (currentUser == null) {return SignIn();}
else {return HomePage();}}
}
//******************************************
class MyUser {
String uid;
MyUser({this.uid ,});
}
//******************************************
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
//This method will need to be updated I guess
Stream<MyUser> get getCurrentUser {
return _auth.onAuthStateChanged.map((FirebaseUser user) => _refereeFromFirebaseUser(user));
}
MyUser _refereeFromFirebaseUser(FirebaseUser _authUser) {
return (_authUser != null) ? MyUser(uid: _authUser.uid) : null;
}
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return user;
} catch (error) {
print(error.toString());
return null;}
}
Future signOut() async {
try {return await _auth.signOut();}
catch (error) {print(error.toString());return null;}
}
}
//******************************************
class HomePage extends StatelessWidget {
final AuthService _auth = AuthService();
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('MyApp2'),
actions: <Widget>[FlatButton.icon(icon: Icon(Icons.person), label: Text('logout'), onPressed: () async {await _auth.signOut();},), ],),
//Following line is very important: this is what I'd like to replicate with new Firebase version
body: Text("My ID is ${currentUser.uid}"),
),);
}
}
//******************************************
class SignIn extends StatefulWidget {
@override _SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String error = '';
String email ;
String password ;
@override Widget build(BuildContext context) {
return Scaffold(
body: Form(key: _formKey,
child: ListView(shrinkWrap: true, children: <Widget>[ SizedBox(height: 60.0),
emailField(), SizedBox(height: 8.0),
passwordField(), SizedBox(height: 24.0),
signInButton(),
Text(error, style: TextStyle(color: Colors.red, fontSize: 16.0),),
],),),);}
RaisedButton signInButton() {
return RaisedButton( child: Text('Sign In'),
onPressed: () async {
if(_formKey.currentState.validate()) {
dynamic result = await _auth.signInWithEmailAndPassword(email, password);
//If successful SignIn, the Provider listening in the Wrapper will automatically load the Home page.
if(result == null) {setState(() {error = 'Could not sign in with those credentials';});}}});
}
TextFormField passwordField() {
return TextFormField(
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long' : null,
onChanged: (val) {setState(() => password = val);},);
}
TextFormField emailField() {
return TextFormField(
validator: (val) => val.isEmpty ? 'Enter an email' : null,
onChanged: (val) {setState(() => email = val);},);
}
}
第一点:当前用户不再是异步的。如果您查看文档,您会发现它不是 return 未来而是用户。如果您想检查身份验证状态更新,只需调用 FirebaseAuth.instance.authStateChanges()。另一件需要注意的事情是,现在包含用户数据的 class 不再被称为 FirebaseUser 而只是 User.
StreamProvider 在提供程序包中仍然可用。在你的问题中,不清楚这个 class 向你提出的问题是什么。
Provider.of<>(context) 仍然可以使用。但是现在您还可以使用这两种替代方法:
- context.watch(),使小部件监听 T
上的变化
- context.read(), returns T 没听过
我能够迁移整个代码。现在是 100% 运行 新 firebase_auth: "^0.18.3"
.
(非常感谢 Net Ninja 提供带有初始代码的网络课程)
这是新的 pubspec.yaml
:
name: flutter_app
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# **** FIREBASE ****
provider: ^4.0.5
firebase_core: "^0.5.2"
firebase_auth: "^0.18.3"
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
这里是 main.dart
:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart'; //New
void main() {
WidgetsFlutterBinding.ensureInitialized();//New
runApp(Initialize());
}
//******************************************
class Initialize extends StatelessWidget {//New
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
@override Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {print("Error-01"); return myCircularProgress();} //to be updated
if (snapshot.connectionState == ConnectionState.done) {return MyApp();}
else {print("loading-02"); return myCircularProgress();}
},);}
Center myCircularProgress() => Center(child: SizedBox(child: CircularProgressIndicator(), height: 100.0, width: 100.0,));
}
//******************************************
class MyApp extends StatelessWidget {
@override Widget build(BuildContext context) {
return StreamProvider<MyUser>.value(
value: AuthService().getCurrentUser,
child: MaterialApp( title: 'MyApp',
home: Wrapper(),),);}
}
//******************************************
class Wrapper extends StatelessWidget {
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
// return either the Home or Authenticate widget
if (currentUser == null) {return SignIn();}
else {return HomePage();}}
}
//******************************************
class MyUser {
String uid;
MyUser({this.uid ,});
}
//******************************************
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
Stream<MyUser> get getCurrentUser {
return _auth.authStateChanges().map((User user) => _refereeFromFirebaseUser(user)); // Also works with "_auth.idTokenChanges()" or "_auth.userChanges()"
}
MyUser _refereeFromFirebaseUser(User _authUser) {
return (_authUser != null) ? MyUser(uid: _authUser.uid) : null;
}
Future signInWithEmailAndPassword(String email, String password) async {
try {
//AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
return user;
} catch (error) {
print(error.toString());
return null;}
}
Future signOut() async {
try {return await _auth.signOut();}
catch (error) {print(error.toString());return null;}
}
}
//******************************************
class HomePage extends StatelessWidget {
final AuthService _auth = AuthService();
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('MyApp v0.18'),
actions: <Widget>[FlatButton.icon(icon: Icon(Icons.person), label: Text('logout'), onPressed: () async {await _auth.signOut();},), ],),
body: Text("My ID is ${currentUser.uid}"),
),);
}
}
//******************************************
class SignIn extends StatefulWidget {
@override _SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String error = '';
String email ;
String password ;
@override Widget build(BuildContext context) {
return Scaffold(
body: Form(key: _formKey,
child: ListView(shrinkWrap: true, children: <Widget>[ SizedBox(height: 60.0),
emailField(), SizedBox(height: 8.0),
passwordField(), SizedBox(height: 24.0),
signInButton(),
Text(error, style: TextStyle(color: Colors.red, fontSize: 16.0),),
],),),);}
RaisedButton signInButton() {
return RaisedButton( child: Text('Sign In'),
onPressed: () async {
if(_formKey.currentState.validate()) {
dynamic result = await _auth.signInWithEmailAndPassword(email, password);
//If successful SignIn, the Provider listening in the Wrapper will automatically load the Home page.
if(result == null) {setState(() {error = 'Could not sign in with those credentials';});}}});
}
TextFormField passwordField() {
return TextFormField(
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long' : null,
onChanged: (val) {setState(() => password = val);},);
}
TextFormField emailField() {
return TextFormField(
validator: (val) => val.isEmpty ? 'Enter an email' : null,
onChanged: (val) {setState(() => email = val);},);
}
}
我有一个运行良好的大型 Flutter
应用程序...
现在,我正在努力更新具有重大更改的 Firebase firebase_auth: ^0.15.5+3
插件(自 2020 年夏季以来)。
当我在应用程序的多个位置检查 MyUser
时,我绝对需要保留我的 StreamProvider
。
我重新创建了一个最小的工作应用程序来专注于我的特定问题。
你能建议我应该如何调整这些:
1- getCurrentUser
in AuthService
: 看来我需要使用 authStateChanges
但不知道如何使用。
2- StreamProvider
in MyApp
:如何调整它以便我可以在我的应用程序中继续使用它而无需更改任何内容。
3- 使用这种方式:final currentUser = Provider.of<MyUser>(context)
然后 currentUser.uid
获取 uid 字符串。
请具体举例说明。
这是我的 puspec.yaml
name: myApp
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# **** FIREBASE ****
firebase_auth: ^0.15.5+3
provider: ^4.0.5
#firebase_core: "^0.5.2"
#firebase_auth: "^0.18.3"
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
这里是之前 Firebase
版本 0.15
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() {
runApp(MyApp());
}
//******************************************
class MyApp extends StatelessWidget {
@override Widget build(BuildContext context) {
//The following StreamProvider is what I am trying to recreate with new Firebase version.
return StreamProvider<MyUser>.value(
value: AuthService().getCurrentUser,
child: MaterialApp( title: 'MyApp',
home: Wrapper(),),);}
}
//******************************************
class Wrapper extends StatelessWidget {
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
// return either the Home or Authenticate widget
if (currentUser == null) {return SignIn();}
else {return HomePage();}}
}
//******************************************
class MyUser {
String uid;
MyUser({this.uid ,});
}
//******************************************
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
//This method will need to be updated I guess
Stream<MyUser> get getCurrentUser {
return _auth.onAuthStateChanged.map((FirebaseUser user) => _refereeFromFirebaseUser(user));
}
MyUser _refereeFromFirebaseUser(FirebaseUser _authUser) {
return (_authUser != null) ? MyUser(uid: _authUser.uid) : null;
}
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return user;
} catch (error) {
print(error.toString());
return null;}
}
Future signOut() async {
try {return await _auth.signOut();}
catch (error) {print(error.toString());return null;}
}
}
//******************************************
class HomePage extends StatelessWidget {
final AuthService _auth = AuthService();
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('MyApp2'),
actions: <Widget>[FlatButton.icon(icon: Icon(Icons.person), label: Text('logout'), onPressed: () async {await _auth.signOut();},), ],),
//Following line is very important: this is what I'd like to replicate with new Firebase version
body: Text("My ID is ${currentUser.uid}"),
),);
}
}
//******************************************
class SignIn extends StatefulWidget {
@override _SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String error = '';
String email ;
String password ;
@override Widget build(BuildContext context) {
return Scaffold(
body: Form(key: _formKey,
child: ListView(shrinkWrap: true, children: <Widget>[ SizedBox(height: 60.0),
emailField(), SizedBox(height: 8.0),
passwordField(), SizedBox(height: 24.0),
signInButton(),
Text(error, style: TextStyle(color: Colors.red, fontSize: 16.0),),
],),),);}
RaisedButton signInButton() {
return RaisedButton( child: Text('Sign In'),
onPressed: () async {
if(_formKey.currentState.validate()) {
dynamic result = await _auth.signInWithEmailAndPassword(email, password);
//If successful SignIn, the Provider listening in the Wrapper will automatically load the Home page.
if(result == null) {setState(() {error = 'Could not sign in with those credentials';});}}});
}
TextFormField passwordField() {
return TextFormField(
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long' : null,
onChanged: (val) {setState(() => password = val);},);
}
TextFormField emailField() {
return TextFormField(
validator: (val) => val.isEmpty ? 'Enter an email' : null,
onChanged: (val) {setState(() => email = val);},);
}
}
第一点:当前用户不再是异步的。如果您查看文档,您会发现它不是 return 未来而是用户。如果您想检查身份验证状态更新,只需调用 FirebaseAuth.instance.authStateChanges()。另一件需要注意的事情是,现在包含用户数据的 class 不再被称为 FirebaseUser 而只是 User.
StreamProvider 在提供程序包中仍然可用。在你的问题中,不清楚这个 class 向你提出的问题是什么。
Provider.of<>(context) 仍然可以使用。但是现在您还可以使用这两种替代方法:
- context.watch(),使小部件监听 T 上的变化
- context.read(), returns T 没听过
我能够迁移整个代码。现在是 100% 运行 新 firebase_auth: "^0.18.3"
.
(非常感谢 Net Ninja 提供带有初始代码的网络课程)
这是新的 pubspec.yaml
:
name: flutter_app
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# **** FIREBASE ****
provider: ^4.0.5
firebase_core: "^0.5.2"
firebase_auth: "^0.18.3"
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
这里是 main.dart
:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart'; //New
void main() {
WidgetsFlutterBinding.ensureInitialized();//New
runApp(Initialize());
}
//******************************************
class Initialize extends StatelessWidget {//New
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
@override Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {print("Error-01"); return myCircularProgress();} //to be updated
if (snapshot.connectionState == ConnectionState.done) {return MyApp();}
else {print("loading-02"); return myCircularProgress();}
},);}
Center myCircularProgress() => Center(child: SizedBox(child: CircularProgressIndicator(), height: 100.0, width: 100.0,));
}
//******************************************
class MyApp extends StatelessWidget {
@override Widget build(BuildContext context) {
return StreamProvider<MyUser>.value(
value: AuthService().getCurrentUser,
child: MaterialApp( title: 'MyApp',
home: Wrapper(),),);}
}
//******************************************
class Wrapper extends StatelessWidget {
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
// return either the Home or Authenticate widget
if (currentUser == null) {return SignIn();}
else {return HomePage();}}
}
//******************************************
class MyUser {
String uid;
MyUser({this.uid ,});
}
//******************************************
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
Stream<MyUser> get getCurrentUser {
return _auth.authStateChanges().map((User user) => _refereeFromFirebaseUser(user)); // Also works with "_auth.idTokenChanges()" or "_auth.userChanges()"
}
MyUser _refereeFromFirebaseUser(User _authUser) {
return (_authUser != null) ? MyUser(uid: _authUser.uid) : null;
}
Future signInWithEmailAndPassword(String email, String password) async {
try {
//AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
return user;
} catch (error) {
print(error.toString());
return null;}
}
Future signOut() async {
try {return await _auth.signOut();}
catch (error) {print(error.toString());return null;}
}
}
//******************************************
class HomePage extends StatelessWidget {
final AuthService _auth = AuthService();
@override Widget build(BuildContext context) {
final currentUser = Provider.of<MyUser>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('MyApp v0.18'),
actions: <Widget>[FlatButton.icon(icon: Icon(Icons.person), label: Text('logout'), onPressed: () async {await _auth.signOut();},), ],),
body: Text("My ID is ${currentUser.uid}"),
),);
}
}
//******************************************
class SignIn extends StatefulWidget {
@override _SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String error = '';
String email ;
String password ;
@override Widget build(BuildContext context) {
return Scaffold(
body: Form(key: _formKey,
child: ListView(shrinkWrap: true, children: <Widget>[ SizedBox(height: 60.0),
emailField(), SizedBox(height: 8.0),
passwordField(), SizedBox(height: 24.0),
signInButton(),
Text(error, style: TextStyle(color: Colors.red, fontSize: 16.0),),
],),),);}
RaisedButton signInButton() {
return RaisedButton( child: Text('Sign In'),
onPressed: () async {
if(_formKey.currentState.validate()) {
dynamic result = await _auth.signInWithEmailAndPassword(email, password);
//If successful SignIn, the Provider listening in the Wrapper will automatically load the Home page.
if(result == null) {setState(() {error = 'Could not sign in with those credentials';});}}});
}
TextFormField passwordField() {
return TextFormField(
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long' : null,
onChanged: (val) {setState(() => password = val);},);
}
TextFormField emailField() {
return TextFormField(
validator: (val) => val.isEmpty ? 'Enter an email' : null,
onChanged: (val) {setState(() => email = val);},);
}
}