gpt4 book ai didi

firebase - 我如何使用从其他页面获取的值

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

我想使用从另一页获取并馈入构造函数的值。我已经尝试过,但是它给的错误为only static member can be accessed in initializers。任何人都可以让我知道如何使用从另一页获取的变量。或者,请让我知道是否有办法从Firebase获取详细信息,即用户电话号码并将其分配给globalNumber
这是我的代码。变量名称为globalNumber

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

var globalNumber;
bool valueExist;

class Pricepage extends StatefulWidget {
@override
_PricepageState createState() => _PricepageState();
}

class _PricepageState extends State<Pricepage> {

var globalNumber;

_PricepageState({this.globalNumber});
StreamSubscription<DocumentSnapshot> subscription;
final DocumentReference documentReference =
Firestore.instance.document("users/$globalNumber"); // (Here this value comes from the previous page this is just the phonenumber of the user from firebase auth)

@override
void initState() {
// TODO: implement initState
super.initState();

subscription = documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.data.containsValue("true")) {
setState(() {
valueExist = true;
});
}
else {
setState(() {
valueExist = false;
});
}
});
}

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: getPrice(),


),
);
}

Widget getPrice() {
try {
if (valueExist) {
return Text('Prices are visibile');
}

else {
return Text('Verify first');
}
}
catch (e) {
print(e);
}
}
}

最佳答案

答复2.0
主要问题在于以下行:

final DocumentReference documentReference =
Firestore.instance.document("users/$globalNumber");

You should not initialize your final variable outside the initState(). You need to do it inside the initState() only. That is why you are getting this error. As in your error only says only static member can be accessed in initializers. And your static member is documentReference only, which has to be initialized inside the initializers, which is in our case is our initState()


这应该起作用
class _PricepageState extends State<Pricepage> {

var globalNumber;

_PricepageState({this.globalNumber});
StreamSubscription<DocumentSnapshot> subscription;
final DocumentReference documentReference;

@override
void initState() {
// TODO: implement initState
super.initState();

// initialise the value here
documentReference = Firestore.instance.document("users/$globalNumber"); // (Here this value comes from the previous page this is just the phonenumber of the user from firebase auth)

subscription = documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.data.containsValue("true")) {
setState(() {
valueExist = true;
});
}
else {
setState(() {
valueExist = false;
});
}
});
}
}
其余代码将保持不变。

关于firebase - 我如何使用从其他页面获取的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63329209/

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