gpt4 book ai didi

dart - Flutter中如何使用UID访问数据库?

转载 作者:IT王子 更新时间:2023-10-29 06:53:53 26 4
gpt4 key购买 nike

我正在使用以下函数来检索 UID:

  FirebaseAuth auth = FirebaseAuth.instance;

getUID() async {
final FirebaseUser user = await auth.currentUser();
final uid = user.uid;
return uid;
}

之后,我想使用 UID 访问正确的数据库文档:

return new StreamBuilder(
stream: Firestore.instance.collection('users').document(getUID()).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return new Text("Loading");
}
var userDocument = snapshot.data;

但是我得到了错误

Future<dynamic> is not a subtype of type "string"

正确的做法是什么?

完整代码

class Settings extends StatelessWidget{
FirebaseAuth auth = FirebaseAuth.instance;

getUID() async {
final FirebaseUser user = await auth.currentUser();
final uid = user.uid;
return uid;
}

static GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Indstillinger"),
),
body: _buildSetting(context),
);
}

Widget _buildSetting(BuildContext context) {
return new StreamBuilder(
stream: Firestore.instance.collection('users').document(getUID()).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return new Text("Loading");
}
var userDocument = snapshot.data;

最佳答案

你需要使用有状态的小部件,比如


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Settings extends StatefulWidget {
@override
_SettingsState createState() {
return _SettingsState();
}
}

class _SettingsState extends State<Settings> {
FirebaseUser user;
String error;

void setUser(FirebaseUser user) {
setState(() {
this.user = user;
this.error = null;
});
}

void setError(e) {
setState(() {
this.user = null;
this.error = e.toString();
});
}

@override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then(setUser).catchError(setError);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Indstillinger"),
),
body: user != null ? _buildSetting(context) : Text("Error: $error"),
);
}

Widget _buildSetting(BuildContext context) {
return new StreamBuilder(
stream: Firestore.instance.collection('users').document(user.uid).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return new Text("Loading");
}
var userDocument = snapshot.data;
// User userDocument here ..........
return new Text(userDocument.toString());
});
}
}


关于dart - Flutter中如何使用UID访问数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54724966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com