Flutter日历Firestore“类型'QuerySnapshot'不是类型'List <EventModel>'的子类型”

时间:2020-11-01 19:26:42

标签: list flutter dart calendar

) 我试图编写一个日历应用程序,其中每个用户都有自己的事件。我想从Firestore中流式传输事件,但始终出现错误消息“类型'QuerySnapshot'不是类型'列表'的子类型”。 Error message

我认为问题出在主文件的StreamBuilder中。

如果有人可以告诉我如何解决这个错误,我将非常高兴。

预先感谢所有尝试帮助我的人。

这是我的主文件:

class KalenderTable extends StatefulWidget {
  @override
  _KalenderTableState createState() => _KalenderTableState();
}

class _KalenderTableState extends State<KalenderTable> {
  CalendarController _controller;
  Map<DateTime, List<dynamic>> _events;
  List<dynamic> _selectedEvents;
  Stream events;

  @override
  void initState() {
    getUserInfogetEvents();
    super.initState();
    _controller = CalendarController();
    _events = {};
    _selectedEvents = [];
  }

  Map<DateTime, List<dynamic>> _groupEvents(List<EventModel> allEvents) {
    Map<DateTime, List<dynamic>> data = {};
    allEvents.forEach((event) {
      DateTime date = DateTime(
          event.eventDate.year, event.eventDate.month, event.eventDate.day, 12);
      if (data[date] == null) data[date] = [];
      data[date].add(event);
    });
    return data;
  }

  getUserInfogetEvents() async {
    Constants.myName = await HelperFunctions.getUserEmailSharedPreference();
    DatabaseKalenderMethods().getUserEvents(Constants.myName).then((snapshots) {
      setState(() {
        events = snapshots;
        print(
            "we got the data + ${events.toString()} this is name ${Constants.myName}");

      });
    });
  }





  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
          stream: events, 
          builder: (context, snapshot) {
            if (snapshot.hasData) {

              List<EventModel> allEvents = snapshot.data;

              if (allEvents.isNotEmpty) {
                _events = _groupEvents(allEvents);
              } else {
                _events = {};
                _selectedEvents = [];
              }
            }
            return SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  TableCalendar(
                    events: _events,
                    initialCalendarFormat: CalendarFormat.twoWeeks,
                    calendarStyle: CalendarStyle(
                        canEventMarkersOverflow: true,
                        todayColor: Colors.orange,
                        selectedColor: Colors.cyan,
                        todayStyle: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0,
                            color: Colors.white)),
                    headerStyle: HeaderStyle(
                      centerHeaderTitle: true,
                      formatButtonDecoration: BoxDecoration(
                        color: Colors.cyan,
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      formatButtonTextStyle: TextStyle(color: Colors.white),
                      formatButtonShowsNext: false,
                    ),
                    startingDayOfWeek: StartingDayOfWeek.monday,
                    onDaySelected: (date, events) {
                      setState(() {
                        _selectedEvents = events;
                      });
                    },
                    builders: CalendarBuilders(
                      selectedDayBuilder: (context, date, events) => Container(
                          margin: const EdgeInsets.all(4.0),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Theme.of(context).primaryColor,
                              borderRadius: BorderRadius.circular(10.0)),
                          child: Text(
                            date.day.toString(),
                            style: TextStyle(color: Colors.white),
                          )),
                      todayDayBuilder: (context, date, events) =>
                        Container(
                          margin: const EdgeInsets.all(4.0),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.orange,
                              borderRadius: BorderRadius.circular(10.0)),
                          child: Text(
                            date.day.toString(),
                            style: TextStyle(color: Colors.white),
                          )),
                    ),
                    calendarController: _controller,
                  ),
                  ..._selectedEvents.map((event) => ContainerKalender(
                    event.title,
                    () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (_) => EventDetailsPage(
                                event: event,
                              )));
                    },
                        () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (_) => EventDetailsPage(
                                event: event,
                              )));
                    },
                  )),
                ],
              ),
            );
          }),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        backgroundColor: Colors.cyan,
        onPressed: () => Navigator.pushNamed(context, 'add_event'),
      ),
    );
  }
}

class EventModel extends DatabaseItem{
  final String id;
  final String title;
  final String description;
  final DateTime eventDate;

  EventModel({this.id,this.title, this.description, this.eventDate}):super(id);

  factory EventModel.fromMap(Map data) {
    return EventModel(
      title: data['title'],
      description: data['description'],
      eventDate: data['event_date'],
    );
  }

  factory EventModel.fromDS(String id, Map<String,dynamic> data) {
    return EventModel(
      id: id,
      title: data['title'],
      description: data['description'],
      eventDate: data['event_date'].toDate(),
    );
  }

  Map<String,dynamic> toMap() {
    return {
      "title":title,
      "description": description,
      "event_date":eventDate,
      "id":id,
    };
  }
}

这是我的Firebase连接:

class DatabaseKalenderMethods {

  getUserEvents(String itIsMyName) async {
    return await Firestore.instance
        .collection("kalender")
        .where('users', arrayContains: itIsMyName)
        .snapshots();
  }
}

1 个答案:

答案 0 :(得分:0)

我猜问题在这里:

const text = "text before

![meme](https://static01.nyt.com/images/2020/01/28/multimedia/28xp-memekid3/28cp-memekid3-articleLarge.jpg?quality=90&auto=webp)

text after"

这是因为(仍在猜测中)List<EventModel> allEvents = snapshot.data; 中的events = snapshots;snapshots

请参见this answer映射流。