import 'dart:async';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = new GoogleSignIn();
class HomePage extends StatefulWidget {
static String tag = 'home-page';
@override
HomePageState createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage> {
Stream<FirebaseUser> _currentUser;
Future<FirebaseUser> signInWithGoogle() async {
print('google signin invoked');
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
FirebaseUser user = await _auth.signInWithGoogle(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
print("signed in " + user.displayName);
return user;
}
@override
Widget build(BuildContext context) {
final lblWelcome = Padding(
padding: EdgeInsets.all(8.0),
child: Text('Frnds Payment',
style: TextStyle(fontSize: 28.0, color: Colors.green)));
final btnSignin = new MaterialButton(
child: const Text('Sign In with Google'),
onPressed: () {
print('button clicked');
_currentUser = signInWithGoogle()?.asStream();
});
final txtOutput = new StreamBuilder<FirebaseUser>(
stream: _currentUser,
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Center(child: new CircularProgressIndicator());
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Center(
child: new Text('${snapshot.data.displayName}'));
}
});
final body = Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[lblWelcome, btnSignin, txtOutput],
),
);
return Scaffold(body: body);
}
}
我是Dart的新手,这是我的第一个应用程序。
登录成功后,我需要显示用户名。
每当我启动应用程序时,它将转到ConnectionState.waiting而不是ConnectionState.none。
同样,它不会在成功登录时使用显示名呈现文本框。重新加载它会渲染显示名称。
最佳答案
ConnectionState.none
表示未分配任何流,
但是你有
setState(() => _currentUser = signInWithGoogle()?.asStream());
这意味着
StreamBuilder
订阅了此流并等待事件。