流初始状态是ConnectionState.waiting而不是null

时间:2018-05-17 07:33:07

标签: firebase dart firebase-authentication flutter

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。

此外,它不会在成功登录时使用displayname呈现文本框。重新加载它会渲染显示名称。

1 个答案:

答案 0 :(得分:1)

ConnectionState.none表示没有分配流, 但你有

setState(() => _currentUser = signInWithGoogle()?.asStream());

这意味着StreamBuilder订阅了此流并等待事件。