gpt4 book ai didi

firebase - 从实时Firestore文档中获取数据

转载 作者:行者123 更新时间:2023-12-03 04:51:47 26 4
gpt4 key购买 nike

我看到StreamBuilder小部件可以解决类似的问题和答案。

就我而言,当我实现它时,我的代码不会等待获取数据而只是继续前进(就我而言,应用程序跳至下一页)。因此,我是否需要构建StreamBuilder窗口小部件,或者是否有一种简单的方法可以实时工作并获取数据?

我注意到我没有使用asterisc使用 async * ,但如果这样做,则身份验证将无法正常工作。

说明:

该代码不输入以下行:

if (!snapshot.hasData)
return new Text('Loading...');
return new Text(
snapshot.data.data['name']
);

此外, print(test);语句还会显示以下内容:
StreamBuilder<DocumentSnapshot>

这是整个部分:
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
LoginScreen.user =
await _auth.signInWithEmailAndPassword(
email: email, password: password);
if (LoginScreen.user != null) {
// get the users data and save them
if (LoginScreen.user.user.uid !=
'IDVwQXAsZas213Va0OIH2IsoU5asdaTfraBJ2') {
Widget test = await StreamBuilder<DocumentSnapshot>(
stream: _firestore
.collection('Employees')
.document(LoginScreen.user.user.uid)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData)
return new Text('Loading...');
return new Text(
snapshot.data.data['name']
);
},
);
print(test);
Navigator.pushReplacementNamed(
context, TabCreator.screenId);
} else {
}
}
} catch (e) {
print(e);
// when getting an erro stop spinner
setState(() {
showSpinner = false;
});
}
}

更新:

我创建了一个新的标准flutter项目,以查看代码中是否还有其他东西弄乱了StreamBuilder。我仍然没有输出。

顺便说一句,当我在onPressed方法中实现以下代码时,我得到了想要的结果:

替代解决方案:
onPressed: () {
DocumentReference documentReference = await Firestore.instance
.collection('Employees')
.document('8nss0gppzNfOBMuRz9H44dv7gSd2');
documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.exists) {
print(datasnapshot.data['name'].toString());
} else {
print('Error!');
}
});
}

这是在标准Flutter项目中实现的实现的 StreamBuilder :
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final _auth = FirebaseAuth.instance;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'Testing',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// DocumentReference documentReference = await Firestore.instance
// .collection('Employees')
// .document('8nss0gppzNfOBMuRz9H44dv7gSd2');
// documentReference.snapshots().listen((datasnapshot) {
// if (datasnapshot.exists) {
// print(datasnapshot.data['name'].toString());
// } else {
// print('Error!');
// }
// });
StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('Employees')
.document('8nss0gppzNfOBMuRz9H44dv7gSd2')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new Text(snapshot.data.data['name']);
}
},
);
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

最佳答案

将您的代码更改为以下内容:

builder: : (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData){
return new Text('Loading...');
}
else{
print(snapshot);
Navigator.pushReplacementNamed(
context, TabCreator.screenId);
}

添加一个 else块,这样当您有数据时,它将输入 else并导航至页面。

另外,您需要在 StreamBuilder方法内使用 build,而不是在用于处理数据处理的 onPressed函数内使用。例如,您可以执行以下操作:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool visible = false;
final firestoreInstance = Firestore.instance;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
Visibility(
child: StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('users')
.document('FIJbBBiplAGorYzdtUQF')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
print(snapshot);
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else if (snapshot.hasData) {
print(snapshot.data.data);
return new Text(snapshot.data.data["age"].toString());
}
return new CircularProgressIndicator();
},
),
visible: visible,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
visible = true;
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

因此,在这里我也使用 Visibility()小部件将其隐藏,但是当单击FAB按钮时,将显示来自Firestore的数据。

关于firebase - 从实时Firestore文档中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61230231/

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