События укладки календаря таблицы на определенную дату — Flutter

#flutter #dart

#flutter #dart

Вопрос:

Я использую Flutter, firestore с настольным календарем.

Вот мой код, который в настоящее время работает, но с небольшим сбоем

               //Initialize Events
              List<Event> eventList = List<Event>();
              //Get events and add them to the list.
              eventsSnapshot.data.documents.forEach((doc) {
                Timestamp _eventDateStart = doc.data['eventDateStart'];
                Timestamp _eventDateFinish = doc.data['eventDateFinish'];
                Event _thisEvent = Event('test',
                      doc.data['eventName'],
                      doc.data['eventPrice'],
                      doc.data['eventDescription'],
                      _eventDateStart.toDate(),
                      _eventDateFinish.toDate());
                print('Event added : ${_thisEvent.eventName.toString()}');
                eventList.add(_thisEvent);
               });
               
              _events = convertToMap(eventList);
  

вот моя конвертокарта

 class Event {
  final String id;
  final String eventName;
  final double eventPrice;
  final String eventDescription;
  final DateTime eventDateStart;
  final DateTime eventDateFinish;

  Event(this.id, this.eventName, this.eventPrice,this.eventDescription, this.eventDateStart, this.eventDateFinish);
}

//method to change calendar item to Map<DateTime,List>
Map<DateTime, List<Event>> convertToMap(List<Event> item) {
  Map<DateTime, List<Event>> resu<

  for (int i = 0; i < item.length; i  ) {
    Event data = item[i];
    //get the date and convert it to a DateTime variable
    DateTime currentDate = data.eventDateStart;
    List<Event> events = [];
    //add the event name to the the eventNames list for the current date.
    //search for another event with the same date and populate the eventNames List.
    for (int j = 0; j < item.length; j  ) {
      //create temp calendarItemData object.
      Event temp = item[j];
      //establish that the temp date is equal to the current date
      if (data.eventDateStart == temp.eventDateStart) {
        //add the event name to the event List.
        events.add(temp);
      } //else continue
    }

    //add the date and the event to the map if the date is not contained in the map
    if (result == null) {
      result = {currentDate: events};
    } else {

      result[currentDate] = events;
    }
  }
  print(result);
  return resu<
}
  

Результат печати выглядит примерно так.

I / flutter (1655): добавлено событие: deuxio I / flutter (1655): добавлено событие: PremierVraiTest I / flutter (1655): добавлено событие: Тест I / flutter ( 1655): {2020-09-17 13:00:00.000: [ Экземпляр «События»], 2020-09-17 12:00:00.000: [Экземпляр ‘События’], 2020-09-18 12:00:00.000: [ Экземпляр ‘События’]}

Проблема сейчас: когда я проверяю свой календарь, я вижу 1 событие из 17 и 1 событие для 18. Событие 17 — это событие с 13:00. Я не вижу второго события.

Ответ №1:

Вы можете скопировать вставить выполнить полный код ниже
Reason 2020-09-17 13:00:00 != 2020-09-17 12:00:00 , при использовании Map result[currentDate] вы не получите 2 события
, которые вы можете использовать только DateTime(year, month, day)
фрагмент кода

   DateTime currentDate = DateTime(data.eventDateStart.year,
      data.eventDateStart.month, data.eventDateStart.day);

  ...
  for (int j = 0; j < item.length; j  ) {
    ...
    if (DateTime(data.eventDateStart.year, data.eventDateStart.month,
            data.eventDateStart.day) ==
        DateTime(temp.eventDateStart.year, temp.eventDateStart.month,
            temp.eventDateStart.day)) {
  

вывод

 I/flutter (21975): {2020-09-17 00:00:00.000: [Instance of 'Event', Instance of 'Event']}
I/flutter (21975): 2
  

полный код

 import 'package:flutter/material.dart';

class Event {
  final String id;
  final String eventName;
  final double eventPrice;
  final String eventDescription;
  final DateTime eventDateStart;
  final DateTime eventDateFinish;

  Event(this.id, this.eventName, this.eventPrice, this.eventDescription,
      this.eventDateStart, this.eventDateFinish);
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Event> eventList = [
    Event("1", "a", 123.0, "a desc", DateTime(2020, 9, 17, 13, 0, 0),
        DateTime(2020, 9, 17, 13, 0, 0)),
    Event("2", "b", 456.0, "b desc", DateTime(2020, 9, 17, 12, 0, 0),
        DateTime(2020, 9, 17, 13, 0, 0))
  ];

  Map<DateTime, List<Event>> convertToMap(List<Event> item) {
    Map<DateTime, List<Event>> resu<
    for (int i = 0; i < item.length; i  ) {
      Event data = item[i];
      //get the date and convert it to a DateTime variable
      //DateTime currentDate = data.eventDateStart;

      DateTime currentDate = DateTime(data.eventDateStart.year,
          data.eventDateStart.month, data.eventDateStart.day);

      List<Event> events = [];
      //add the event name to the the eventNames list for the current date.
      //search for another event with the same date and populate the eventNames List.
      for (int j = 0; j < item.length; j  ) {
        //create temp calendarItemData object.
        Event temp = item[j];
        //establish that the temp date is equal to the current date
        if (DateTime(data.eventDateStart.year, data.eventDateStart.month,
                data.eventDateStart.day) ==
            DateTime(temp.eventDateStart.year, temp.eventDateStart.month,
                temp.eventDateStart.day)) {
          //add the event name to the event List.
          events.add(temp);
        } //else continue
      }

      //add the date and the event to the map if the date is not contained in the map
      if (result == null) {
        result = {currentDate: events};
      } else {
        result[currentDate] = events;
      }
    }
    print(result);
    print(result[DateTime(2020, 9, 17, 0, 0, 0)].length);
    return resu<
  }

  void _incrementCounter() {
    convertToMap(eventList);
    setState(() {
      _counter  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}