【发布时间】:2021-04-25 03:18:29
【问题描述】:
我正在使用 Firebase(实时数据库)开发一个项目。在这个项目中,我将有一个主屏幕,根据用户将有几个按钮。按钮信息将存储在实时数据库中。这基本上是一个家庭自动化项目。
这就是我的数据库的外观:
数量,表示该用户有多少个按钮。 button1 和 button2 具有按钮特性。所以我正在尝试做的是。
当用户登录时。我有一个 Streambuilder 将检查数量是否有数据。如果我有 if 将在 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),),
),
],
),
),
);
}
}```
【问题讨论】:
标签: firebase flutter firebase-realtime-database flutter-layout