首页 > 解决方案 > 如何从firebase中的另一个表中获取数据?

问题描述

您好,我在 Firebase 中有两张表,即“路线”和“巴士站”。当我点击卡片到另一个页面时,我想检索另一个数据,但我收到错误。要求在 CustomCard 类中调用数据,但它不是正确的数据库。

显示卡的主页,效果很好:

import 'package:cloud_firestore/cloud_firestore.dart';
class Home extends StatefulWidget {
  @override
  _HomeState createState() => new _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      // appBar: new AppBar(
      //   title: new Text('Home',),
      // ),
      body: Center(
        child: Container(
          color: Colors.red[400],
          padding: const EdgeInsets.all(20.0),
          child: StreamBuilder<QuerySnapshot>(
            stream: Firestore.instance.collection('routes').snapshots(),
            builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
              if (snapshot.hasError)
                return new Text('Error: ${snapshot.error}');
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return new Text('Loading....');
                default:
                  return new ListView(
                    children: snapshot.data.documents.map((DocumentSnapshot document) {
                      return new CustomCard(
                        //name: document['name'],
                        routenum: document['routenum'].toString(),
                        from: document['from'],
                        to: document['to'],
                        via: document['via'],
                      );
                    }).toList(),
                  );
              }
            },
          ),
        ),
      ),
    );
  }
}
class CustomCard extends StatelessWidget {
  CustomCard({@required  this.routenum, this.from, this.to, this.via, });

  final routenum;
  final from;
  final to;
  final via;

  @override
  Widget build(BuildContext context) {
    return Card(
        color: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        elevation: 25,
        margin: EdgeInsets.all(12),
        child: InkWell(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                  //builder: (context) => Stations(),
                  builder: (context) => BusInfo(routenum: routenum, from: from, to: to, via: via, ), 
                )
            );
          },
          child: Container(

            padding: const EdgeInsets.all(30.0),
        child: Column(
          children: <Widget>[
            Text("Route Number :" +" " + routenum, style: GoogleFonts.baloo(
              fontWeight: FontWeight.bold,
              fontStyle: FontStyle.italic,
              fontSize: 15,
              ),
            ),
            RichText(
              text: TextSpan(
                text: 'From : ',
                style: GoogleFonts.poppins(
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
                children: <TextSpan>[
                  TextSpan(
                    text: '$from',
                    style: GoogleFonts.viga(
                      color: Colors.blue[800],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ]
              ),
            ),
            Text("via" + " " + via , style: GoogleFonts.poppins(),
            ),
            RichText(
              text: TextSpan(
                text: 'To : ',
                style: GoogleFonts.poppins(
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
                children: <TextSpan>[
                  TextSpan(
                    text: '$to',
                    style: GoogleFonts.viga(
                      color: Colors.blue[800],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ]
              ),
            ),
            Text("(or Vice Versa)", style: GoogleFonts.montserrat()),
          ],
        ),
      ),
    ));
  }
}

下面是我想在我的firebase中带来作为busstations数据的代码:

class Stations extends StatefulWidget {
  @override
  _StationsState createState() => _StationsState();
}

class _StationsState extends State<Stations> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Center(
        child: Container(
          //color: Colors.red[400],
          padding: const EdgeInsets.all(20.0),
          child: StreamBuilder<QuerySnapshot>(
            stream: Firestore.instance.collection('busstops').snapshots(),
            builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
              if (snapshot.hasError)
                return new Text('Error: ${snapshot.error}');
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return new Text('Loading....');
                default:
                  return new ListView(
                    children: snapshot.data.documents.map((DocumentSnapshot document) {
                      return new CustomTable(
                        //name: document['name'],
                        title: document['title'],
                        station1: document['station1'],
                        station2: document['station2'],
                        station3: document['station3'],
                        station4: document['station4'],
                        station5: document['station5'],
                        station6: document['station6'],
                        station7: document['station7'],
                        station8: document['station8'],
                      );
                    }).toList(),
                  );
              }
            },
          ),
        ),
      ),
    );
  }
}
class CustomTable extends StatelessWidget {
  CustomTable({@required this.title, this.station1, this.station2, this.station3, this.station4, this.station5, this.station6, this.station7, this.station8});

  final title;
  final station1;
  final station2;
  final station3;
  final station4;
  final station5;
  final station6;
  final station7;
  final station8;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        Center(
          child: Text(
            title,
            style: TextStyle(color: Colors.black,),
          ),
        )
      ],
    );
  }
}

这是我希望来自 bussops 的数据以表格形式而不是路线显示的地方。

class BusInfo extends StatelessWidget {
  BusInfo({@required this.routenum, this.from, this.to, this.via});

  final routenum;
  final from;
  final to;
  final via;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: Text(routenum),
            backgroundColor: Color(0xFFBDBDBD),
            elevation: 3,
            bottom: TabBar(indicatorSize: TabBarIndicatorSize.label, tabs: [
              Tab(
                child: Align(
                  alignment: Alignment.center,
                  child: Text("Route Info"),
                ),
              ),
              Tab(
                child: Align(
                  alignment: Alignment.center,
                  child: Text("Timetable"),
                ),
              ),
            ]),
          ),
          body: TabBarView(children: [
             Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(routenum),
                Text(from),
                Text(via),
                Text(to),
                RaisedButton(
                    child: Text('Back To HomeScreen'),
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    onPressed: () => Navigator.pop(context)),
              ]),
        ),
            Icon(Icons.movie),
            // Icon(Icons.games),
          ]),
        ))
     );
  }
}

标签: firebasefluttergoogle-cloud-firestore

解决方案


推荐阅读