如何在另一个小部件中获取 firestore 数据

How to get firestore data in another widget

到目前为止,该应用程序可以做什么: 到目前为止,我有一个应用程序可以在 Google 从 Firestore 获取坐标的地图上显示标记。

我想要的:我希望当用户按下一个标记时,他会来到另一个屏幕,上面会显示更多数据(数据也在 firestore 上) .

问题:我不知道如何获取要显示详情的屏幕上的数据(例如姓名)

我有一个 onTap 函数,它调用 goToDetailPage()

这就是 goToDetailPage() 函数:

void goToDetailPage() {
    Navigator.of(context).push(new MaterialPageRoute(
        builder: (BuildContext context) => new detailPage()));
  }

这是“绘制”标记的代码:

 void initMarker(specify, specifyId) async {
    var markerIdVal = specifyId;
    final MarkerId markerId = MarkerId(markerIdVal);
    final Marker marker = Marker(
        markerId: markerId,
        position:
            LatLng(specify['location'].latitude, specify['location'].longitude),
        infoWindow: InfoWindow(title: specify['name'], snippet: 'Shop'),
        onTap: () {
          goToDetailPage();
        });
    print(specify['location'].latitude);
    nameTest = specify['name'];
    setState(() {
      markers[markerId] = marker;
      print(markerId.toString() + '__________________________');
    });
  }

这是详情页面的代码:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Page'),
      ),
      body: Column(children: <Widget>[Text(specify['name'])]),
    );

问题是详细页面中指定['name']中的指定有红色下划线,我不知道这是什么原因。

第二页:

class Tester extends StatefulWidget {

  String dataFromLastPage;
  Tester({Key key, this.dataFromLastPage}) : super(key: key);

  @override
  _TesterState createState() => _TesterState();
}

class _TesterState extends State<Tester> {
  @override
  Widget build(BuildContext context) {
    return Text(widget.dataFromLastPage); //"thisWillGoToTheNextPage!"
  }
}

导航到该页面时,发送这样的数据:

Navigator.of(context).push(new MaterialPageRoute(
        builder: (BuildContext context) => new Tester(dataFromLastPage: 'thisWillGoToTheNextPage!')));

尝试按照文档所说的进行操作:https://firebase.flutter.dev/docs/firestore/usage/#realtime-changes

但是,文档中有几件事没有具体说明,例如

  • 首先要使用firestore,你需要初始化你的firestore应用程序,为此你只需在dart文件的main方法中写一段特定的代码
void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
  • 要连接到您的 firestore 数据库,只需输入您的小部件构建函数

    CollectionReference <Variable name> = FirebaseFirestore.instance.collection(<Name of collection as string>);

  • 现在,如果您正在创建一个列表,您可以简单地使用一个 StreamBuilder 函数并通过(按照文档中给出的初始化快照)获取文档中的数据

snapshot.data.docs[index].data()[<Identifier of your document such as
 'Name' or 'location'>]