flutter firebase auth текущая электронная почта для заголовка панели приложения - PullRequest
0 голосов
/ 06 сентября 2018

Пользователь уже входит в приложение, используя адрес электронной почты Firebase. Как сделать так, чтобы заголовок панели приложений был текущим пользователем?

class _HomePageState extends State<HomePage> {

  final  Future<String> userEmail = FirebaseAuth.instance.currentUser().then((FirebaseUser user) => user.email);
  var e = "";

  @override
  Widget build(BuildContext context) {

    return new Scaffold(
        appBar: new AppBar(
        backgroundColor: Colors.black,
          title: Text('userEmail'),
          actions: <Widget>[
            new FlatButton(
                onPressed: _signOut,
                child: new Text('logout', style: new TextStyle(fontSize: 17.0, color: Colors.white))
            ),

          ],
        ),
        body: new Center(
          child: new Text(
            e,
            style: new TextStyle(fontSize: 32.0),
          ),
        )
    );
  }
}

1 Ответ

0 голосов
/ 06 сентября 2018

Вам нужно позвонить setState() после того, как у вас появится новый пользователь.

В своем коде вы создаете Future<String> email, но не можете извлечь выгоду из возможной оценки user.email.

Я рекомендую создать нефинальную переменную для хранения вашего FirebaseUser, а затем вызвать запрос на это в методе State initState().

FirebaseUser currentUser; // not final

Цель состоит в том, чтобы в конечном итоге иметь возможность вызывать setState() после получения FirebaseUser (поскольку это асинхронно).

FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
   setState(() { // call setState to rebuild the view
     this.currentUser = user;
   });
});

Важно отметить, что вы должны создать свой пользовательский интерфейс для всех возможных состояний currentUser:

  • null (до завершения вызова)
  • и, ну, не ноль.

Поэтому вам нужно убедиться, что вы обрабатываете дело null с логикой, подобной:

String _email() {
    if (currentUser != null) {
      return currentUser.email;
    } else {
      return "no current user";
    }
}

Ниже приведен пример, адаптированный из вашего кода:

class _HomePageState extends State<HomePage> {
  FirebaseUser currentUser;

  @override
  void initState() {
    super.initState();
    _loadCurrentUser();
  }

  void _loadCurrentUser() {
    FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
      setState(() { // call setState to rebuild the view
        this.currentUser = user;
      });
    });
  }

  String _email() {
    if (currentUser != null) {
      return currentUser.email;
    } else {
      return "no current user";
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          backgroundColor: Colors.black,
          title: Text('userEmail'),
          actions: <Widget>[
            new FlatButton(
                onPressed: _signOut,
                child: new Text('logout',
                    style: new TextStyle(fontSize: 17.0, color: Colors.white))),
          ],
        ),
        body: new Center(
          child: new Text(
            _email(),
            style: new TextStyle(fontSize: 32.0),
          ),
        ));
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...