如何在 Flutter 中不使用 FutureBuilder 或 StreamBuilder 的情况下从 Firebase 获取单个数据

lit*_*cal 3 dart firebase flutter google-cloud-firestore

我想从 Firestore 检索单个数据或字段。就像本例中user1firstName,lastNametitle

在此输入图像描述

我已经浏览了FlutterFire文档,它用于FutureBuilder从 Firestore 读取数据。我也在 Stack Overflow 上搜索过这个问题,但没有得到任何完美的答案。

lit*_*cal 6

回答我自己的问题,因为我没有找到这个问题的完美答案。

//Initialising as 'loading..' because text widget (where you'll be using these variables) can't be null
String firstName = 'loading...'
String lastName = 'loading...'
String title = 'loading...'

class Screen extends StatefulWidget {
  @override
  _ScreenState createState() => _ScreenState();
}

class _ScreenState extends State<Screen> {

  //Creating a reference to the collection 'users'
  CollectionReference collectionReference =
    FirebaseFirestore.instance.collection('users');

  //This function will set the values to firstName, lastName and title from the data fetched from firestore 
  void getUsersData() {
    collectionReferenceToOrderacWeb.doc('user1').get().then((value) {

      //'value' is the instance of 'DocumentSnapshot'
      //'value.data()' contains all the data inside a document in the form of 'dictionary'
      var fields = value.data();

      //Using 'setState' to update the user's data inside the app
      //firstName, lastName and title are 'initialised variables'
      setState(() {
        firstName = fields['firstName'];
        lastName = fields['lastName'];
        title = fields['title'];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Run Code Online (Sandbox Code Playgroud)