我正在使用Firebase(实时数据库)进行项目。在这个项目中,我将有一个主屏幕,其中将根据用户有几个按钮。Buttons信息将存储在实时数据库中。这基本上是一个家庭自动化项目。
这是我的数据库的外观:
数量,表示该用户有多少个按钮。button1和button2具有按钮特性。所以我想做的是。
当用户登录时。我有一个Streambuilder,它将检查数量是否有数据。如果有,它将在For循环内运行,这将在用户屏幕中创建按钮。
我在从数据库获取特定值时遇到问题,例如,获取数量并将其存储到主屏幕中的变量中。
这就是我尝试获取数量的方式(稍后,我还将使用此代码获取其他值),但是它不起作用:
Future<int> receive_quantity() async{
final FirebaseUser user = await _auth.currentUser();
var snapshot = databaseReference.child(user.uid+"/buttons"+"/quantity").once();
var result;
await snapshot.then((value) => result = value);
print(result);
return result;
}
我得到的错误:
_TypeError (type 'DataSnapshot' is not a subtype of type 'FutureOr<int>')
我的StreamBuilder:
body: StreamBuilder(
stream: _auth.getButtonQuantity(),
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError || snapshot.hasError){
return Container(color: Colors.red);
}
if (!snapshot.hasData || !snapshot.hasData){
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasData || snapshot.hasData){
return GridView.count(
padding: EdgeInsets.all(15),
crossAxisSpacing: 20.0,
mainAxisSpacing: 20.0,
crossAxisCount: 3,
children: [
for (int i = 0; i < buttonquant; i++){
Button(),
},
GestureDetector(
onTap: () async{
_auth.receive_quantity();
},
child: Container(
color: Colors.black,
width: 150,
height: 150,
child: Icon(Icons.add, color: Colors.white,),
),
),
],
);
}
}
),
我的按钮:
class Button extends StatelessWidget {
const Button({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
},
child: Container(
width: 150,
height: 150,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(15)
),
child: Stack(
children: [
Positioned(
top: 10,
left: 10,
child: Icon(
Icons.lightbulb,
size: 35,
color: Colors.white,
),
),
Positioned(
top: 95,
left: 15,
child: Text("Televisao", style: TextStyle(color: Colors.white),),
),
],
),
),
);
}
}```
您需要做的是获取快照的值,而不是直接使用快照:
Future<int> receive_quantity() async{
final FirebaseUser user = await _auth.currentUser();
var snapshot = await databaseReference.child(user.uid+"/buttons"+"/quantity").once();
var result = snapshot.value; //get the value here
print(result);
return result;
}
通常,这就是您获得价值的方式:
databaseReference.once().then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句