FirebaseFirestore.get返回null-清除器

FirebaseFirestore.get返回null-清除器,firebase,flutter,dart,google-cloud-firestore,Firebase,Flutter,Dart,Google Cloud Firestore,我正在尝试从Firestore获取数据 class _TestState extends State<Test> { bool abcd; final adsRef = FirebaseFirestore.instance.collection('All ads'); getData(){ adsRef.get().then((snap) { snap.docs.forEach((doc) { abcd=doc.data().isEmpty; }); }); }

我正在尝试从Firestore获取数据

class _TestState extends State<Test> {
bool abcd;
final adsRef = FirebaseFirestore.instance.collection('All ads');
getData(){
adsRef.get().then((snap) {
  snap.docs.forEach((doc) { 
    abcd=doc.data().isEmpty;
  });
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: new AppBar(
    title: Text("TestPage"),
  ),
  body: FlatButton(
    onPressed: () {
      print(abcd);
    },
    child: Text("data"),
  ),
  );
  }
  }
class\u TestState扩展状态{
布尔abcd;
final adsRef=firebaseforestore.instance.collection('All ads');
getData(){
adsRef.get().then((捕捉){
snap.docs.forEach((doc){
abcd=doc.data().isEmpty;
});
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:新的appBar(
标题:文本(“测试页”),
),
主体:扁平按钮(
已按下:(){
打印(abcd);
},
子项:文本(“数据”),
),
);
}
}
下面是数据库:

我试着获取
doc.id
doc.exists
,等等
但是 它正在返回“null”


PS:我是firebase的新手。

数据是从firebase/Firestore(以及大多数现代云API)异步加载的,需要通过
setState()
调用(或另一个状态管理原语)传递到UI

你应该:

  • 开始在类的
    initState
    方法中加载数据
  • 然后在数据可用(或更改)时调用
    setState()
  • 这将触发
    build()
    方法,然后您可以在其中使用来自状态的数据
  • 比如:

    class _TestState extends State<Test> {
      bool abcd;
      final adsRef = FirebaseFirestore.instance.collection('All ads');
    
      @override
      void initState() {
        super.initState();
    
        adsRef.get().then((snap) {
          snap.docs.forEach((doc) { 
            setState(() {
              abcd=doc.data().isEmpty;
            });
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: new AppBar(
            title: Text("TestPage"),
          ),
          body: FlatButton(
            onPressed: () {
              print(abcd);
            },
            child: Text("data"),
          ),
        );
      }
    }
    
    class\u TestState扩展状态{
    布尔abcd;
    final adsRef=firebaseforestore.instance.collection('All ads');
    @凌驾
    void initState(){
    super.initState();
    adsRef.get().then((捕捉){
    snap.docs.forEach((doc){
    设置状态(){
    abcd=doc.data().isEmpty;
    });
    });
    });
    }
    @凌驾
    小部件构建(构建上下文){
    返回脚手架(
    appBar:新的appBar(
    标题:文本(“测试页”),
    ),
    主体:扁平按钮(
    已按下:(){
    打印(abcd);
    },
    子项:文本(“数据”),
    ),
    );
    }
    }
    
    您需要使用“异步/等待”从firebase获取数据

    异步getData()

    打电话


    data=像这样等待getData()。

    您在哪里调用
    getData()