如何获取日历的地图列表?[扑] [英] How to fetch a list of maps to a calendar? [Flutter]

查看:72
本文介绍了如何获取日历的地图列表?[扑]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个json对象-

  {错误":"0","message":知道了!",数据": [{状态":假,"_id":"5e04a27692928701258b9b06","group_id":"5df8aaae2f85481f6e31db59","date":"2019-12-29T00:00:00.000Z","title":新任务",优先级":5"description":只是一个描述",任务": [],"created_date":"2019-12-26T12:07:18.301Z","__v":0}]} 

我正在使用此插件在我的应用程序中实现日历-

完整代码

  import'package:flutter/material.dart';导入'package:table_calendar/table_calendar.dart';//要解析此JSON数据,请执行////最终事件= eventFromJson(jsonString);导入'dart:convert';事件eventFromJson(String str)=>Event.fromJson(json.decode(str));字符串eventToJson(Event data)=>json.encode(data.toJson());班级活动{字符串错误;字符串信息;列表<基准>数据;事件({这个错误,这条信息,这个数据,});工厂Event.fromJson(Map< String,dynamic> json)=>事件(错误:json ["error"],消息:json ["message"],数据:List< Datum> .from(json ["data"].map((x)=> Datum.fromJson(x))),);Map< String,dynamic>toJson()=>{错误":错误,消息":消息,数据":List< dynamic> .from(data.map((x)=> x.toJson())),};}Datum类{布尔状态;字符串ID;字符串groupId;DateTime日期;字符串标题;int优先级;字符串描述;列出< dynamic>任务;DateTime createdDate;诠释v;基准({这个状态this.id,this.groupId,这个日期这个标题这个优先此说明,这个任务,this.createdDate这个});factory Datum.fromJson(Map< String,dynamic> json)=>基准(状态:json ["status"],id:json ["_ id"],groupId:json ["group_id"],日期:DateTime.parse(json ["date"]),标题:json ["title"],优先级:json ["priority"],描述:json ["description"],任务:List< dynamic> .from(json ["tasks"].map((x)=> x)),createdDate:DateTime.parse(json ["created_date"]),v:json ["__ v"],);Map< String,dynamic>toJson()=>{状态":状态,"_id":id,"group_id":groupId,日期":date.toIso8601String(),标题":标题,优先级":优先级,说明":说明,任务":List< dynamic> .from(tasks.map((x)=> x)),"created_date":createdDate.toIso8601String(),"__v":v,};}void main()=>runApp(MyApp());MyApp类扩展了StatelessWidget {@override窗口小部件build(BuildContext context){返回MaterialApp(标题:"Flutter演示",主题:ThemeData(primarySwatch:Colors.blue,),主页:MyHomePage(标题:"Flutter演示首页"),);}}类MyHomePage扩展了StatefulWidget {MyHomePage({Key key,this.title}):超级(key:key);最终的字符串标题;@override_MyHomePageState createState()=>_MyHomePageState();}类_MyHomePageState扩展State< MyHomePage>与TickerProviderStateMixin {列出_selectedEvents;int _counter = 0;Map< DateTime,List>_events;CalendarController _calendarController;AnimationController _animationController;void _incrementCounter(){setState((){_counter ++;});}Future< Map< DateTime,List>>getTask()异步{Map< DateTime,List>mapFetch = {};等待Future.delayed(const Duration(seconds:3),(){});/*字符串链接= baseURL + fetchTodoByDate;var res = await http.post(Uri.encodeFull(link),标头:{"Accept":"application/json"}));如果(res.statusCode == 200){//在此处创建提取逻辑时需要帮助} */字符串responseString ='''{错误":"0","message":知道了!",数据": [{状态":假,"_id":"5e04a27692928701258b9b06","group_id":"5df8aaae2f85481f6e31db59","date":"2019-12-29T00:00:00.000Z","title":新任务",优先级":5"description":只是一个描述",任务": [],"created_date":"2019-12-26T12:07:18.301Z","__v":0},{状态":假,"_id":"5e04a27692928701258b9b06","group_id":"5df8aaae2f85481f6e31db59","date":"2019-12-30T00:00:00.000Z","title":"abc",优先级":5"description":只是一个描述",任务": [],"created_date":"2019-12-26T12:07:18.301Z","__v":0}]}''';事件event = eventFromJson(responseString);for(int i = 0; i< event.data.length; i ++){mapFetch [event.data [i] .date] = [event.data [i] .title];}返回mapFetch;}void _onDaySelected(DateTime day,List events){print('CALLBACK:_onDaySelected');setState((){_selectedEvents =事件;});}@override无效的initState(){final _selectedDay = DateTime.now();_selectedEvents = [];_calendarController = CalendarController();_animationController = AnimationController(vsync:这个,duration:const Duration(毫秒:400),);_animationController.forward();WidgetsBinding.instance.addPostFrameCallback((_){getTask().then((val)=> setState((){_events = val;}));//print('$ {_ events.toString()}');});super.initState();}@override无效dispose(){_calendarController.dispose();super.dispose();}@override窗口小部件build(BuildContext context){返回脚手架(appBar:AppBar(标题:文本(widget.title),),身体:中心(子:列(mainAxisAlignment:MainAxisAlignment.center,子代:< Widget> [_buildTableCalendarWithBuilders(),const SizedBox(高度:8.0),const SizedBox(高度:8.0),Expanded(child:_buildEventList()),],),),floatActionButton:FloatingActionButton(onPressed:_incrementCounter,工具提示:增量",子级:Icon(Icons.add),),);}小部件_buildTableCalendarWithBuilders(){返回TableCalendar(//语言环境:"pl_PL",calendarController:_calendarController,事件:_events,//假期:_holidays,initialCalendarFormat:CalendarFormat.month,formatAnimation:FormatAnimation.slide,startingDayOfWeek:StartingDayOfWeek.sunday,availableGestures:AvailableGestures.all,availableCalendarFormats:const {CalendarFormat.month:'',CalendarFormat.week:",},calendarStyle:CalendarStyle(outsideDaysVisible:false,weekendStyle:TextStyle().copyWith(颜色:Colors.blue [800]),holidayStyle:TextStyle().copyWith(颜色:Colors.blue [800]),),daysOfWeekStyle:DaysOfWeekStyle(weekendStyle:TextStyle().copyWith(颜色:Colors.blue [600]),),headerStyle:HeaderStyle(centerHeaderTitle:正确,formatButtonVisible:否,),建设者:CalendarBuilders(selectedDayBuilder :(上下文,日期,_){返回FadeTransition(透明度:Tween(开始:0.0,结束:1.0).animate(_animationController),子代:集装箱(边距:const EdgeInsets.all(4.0),填充:const EdgeInsets.only(顶部:5.0,左侧:6.0),颜色:Colors.deepOrange [300],宽度:100,高度:100,子代:文字("$ {date.day}",样式:TextStyle().copyWith(fontSize:16.0),),),);},todayDayBuilder :(上下文,日期,_){返回容器(边距:const EdgeInsets.all(4.0),填充:const EdgeInsets.only(顶部:5.0,左侧:6.0),颜色:Colors.amber [400],宽度:100,高度:100,子代:文字("$ {date.day}",样式:TextStyle().copyWith(fontSize:16.0),),);},markersBuilder :(上下文,日期,事件,假期){最后的孩子=< Widget> [];如果(events.isNotEmpty){children.add(定位(右:1底部:1子代:_buildEventsMarker(date,events),),);}如果(holidays.isNotEmpty){children.add(定位(右:-2,上:-2,子代:_buildHolidaysMarker(),),);}归还孩子;},),onDaySelected :(日期,事件){_onDaySelected(日期,事件);_animationController.forward(from:0.0);},onVisibleDaysChanged:_onVisibleDaysChanged,);}无效_onVisibleDaysChanged(日期时间在前,日期时间在后,CalendarFormat格式){print('CALLBACK:_onVisibleDaysChanged');}小部件_buildEventsMarker(DateTime日期,列出事件){返回AnimatedContainer(duration:const Duration(毫秒:300),装饰:BoxDecoration(形状:BoxShape.rectangle,颜色:_calendarController.isSelected(date)?颜色.棕色[500]:_calendarController.isToday(date)?颜色.褐色[300]:Colors.blue [400],),宽度:16.0,高度:16.0,孩子:中心(子代:文字("$ {events.length}",样式:TextStyle().copyWith(颜色:Colors.white,fontSize:12.0,),),),);}小部件_buildHolidaysMarker(){返回图标(Icons.add_box,大小:20.0,颜色:Colors.blueGrey [800],);}小部件_buildEventList(){返回ListView(子级:_selectedEvents.map((event)=> Container(装饰:BoxDecoration(border:Border.all(width:0.8),borderRadius:BorderRadius.circular(12.0),),利润:const EdgeInsets.symmetric(水平:8.0,垂直:4.0),子代:ListTile(标题:Text(event.toString()),onTap:()=>打印('$ event tapped!'),),)).toList(),);}} 

I have a json object here -

{
    "error": "0",
    "message": "Got it!",
    "data": [
        {
            "status": false,
            "_id": "5e04a27692928701258b9b06",
            "group_id": "5df8aaae2f85481f6e31db59",
            "date": "2019-12-29T00:00:00.000Z",
            "title": "new task",
            "priority": 5,
            "description": "just a description",
            "tasks": [],
            "created_date": "2019-12-26T12:07:18.301Z",
            "__v": 0
        }
    ]
}

I am using this plugin to implement a calendar in my application - https://github.com/aleksanderwozniak/table_calendar.

I want to fetch the json objects in the format of Map <DateTime, List> (the plugin has an assertion for using Map <DateTime, List> for displaying events) where the "date" parameter should be mapped to "title" parameter.

the plugin uses initState to create a few hard coded events -


 Map<DateTime, List> _events;
  @override
  void initState() {
    super.initState();

    final _selectedDay = DateTime.now();


    _events = {_selectedDay : ["event 1"]};
  }

Could i get some help on how to fetch a json object and convert it to a format of Map<DateTime, List>? Fetching the data on initState to _events ` should be fine.

data model -

class Post {
  dynamic markComplete;
  dynamic groupID;
  dynamic date;
  dynamic taskName;
  dynamic taskID;
//dynamic subtasks;

  dynamic priority;
  dynamic description;

/// IMPLEMENT PARAMETERS AFTER CONFIRMING WITH VAMSHI

  Post({
    this.markComplete,
    this.groupID,
    this.taskID,
    this.date,
    this.taskName,
//    this.subtasks,

    this.priority,
    this.description,
  });

/// MIGHT NEED TO CHANGE JSON VALUES; CONFIRM FROM VAMSHI
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        markComplete : json['status'],
        groupID : json['group_id'],
      taskID: json["_id"],
      date : json['date'],
      taskName : json['title'],
//      subtasks : json['subTasks'],

      priority : json['priority'],
      description : json['description']
    );
  }



  Map toMapFetch() {
    var map = new Map<dynamic, dynamic>();
//    map['status'] = markComplete;
//    map["group_id"] = taskid;
//    map['date'] = date;
    map['title'] = taskName;
//    map['subTasks'] = subtasks;
//
//    map['priority'] = priority;
//    map['description'] = description;


    return map;
  }
}

method to fetch -

Future<Map<DateTime, List>> getTask() async {
  Map<DateTime, List> mapFetch;
  String link = baseURL + fetchTodoByDate;
  var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json"});
  if (res.statusCode == 200) {
 // need help in creating fetch logic here
  }
return mapFetch;
}

data model =

class dataArray {
//  final dynamic status;
  final dynamic id;
  final dynamic groupName;

//  final dynamic description;
//  final dynamic created_date;
//  final dynamic v;


  dataArray(this.groupName, this.id);


  dataArray.fromJson(Map jsonMap)
      : groupName = jsonMap['name'],
        id = jsonMap['_id'];


  Map toMapData(){
    var mapGroup = new Map<String, dynamic>();
    mapGroup["name"] = groupName;
    mapGroup['_id'] = id;
    return mapGroup;

  }

}

updated getTask method =

  Future<List<dataArray>> getTask() async {


    List<dataArray> groupMap;
    String link = baseURL + fetchGroups;
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
//  print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data["data"] as List;

      final demoJsonMapEntries = rest.map((data) {
        return MapEntry(DateTime.parse(data['created_date']), data['name']);
      });

      demoJsonMapEntries.forEach((e) {
        // Normalize the `date` - this is necessary to ensure proper `Map` behavior
        final key = DateTime.utc(e.key.year, e.key.month, e.key.day, 12);

        _events.update(key, (list) => list..add(e.value), ifAbsent: () => [e.value]);
      });
      print(demoJsonMapEntries);
    }
    print("PRINTING MAP = $groupMap");
 return groupMap;
  }

解决方案

You can copy paste run full code below
Simulate API call with 3 seconds delay
Suppose you have two event on 12/29 and 12/30 , then parse with Event event = eventFromJson(responseString); and return mapFetch after for loop
You can get full Event class define in full code

code snippet

WidgetsBinding.instance.addPostFrameCallback((_) {
      getTask().then((val) => setState(() {
            _events = val;
          }));

    });

...
Future<Map<DateTime, List>> getTask() async {
    Map<DateTime, List> mapFetch = {};

    await Future.delayed(const Duration(seconds: 3), () {});

    /*String link = baseURL + fetchTodoByDate;
    var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    if (res.statusCode == 200) {
      // need help in creating fetch logic here
    }*/

    String responseString = '''
    {
    "error": "0",
    "message": "Got it!",
    "data": [
        {
            "status": false,
            "_id": "5e04a27692928701258b9b06",
            "group_id": "5df8aaae2f85481f6e31db59",
            "date": "2019-12-29T00:00:00.000Z",
            "title": "new task",
            "priority": 5,
            "description": "just a description",
            "tasks": [],
            "created_date": "2019-12-26T12:07:18.301Z",
            "__v": 0
        },
        {
            "status": false,
            "_id": "5e04a27692928701258b9b06",
            "group_id": "5df8aaae2f85481f6e31db59",
            "date": "2019-12-30T00:00:00.000Z",
            "title": "abc",
            "priority": 5,
            "description": "just a description",
            "tasks": [],
            "created_date": "2019-12-26T12:07:18.301Z",
            "__v": 0
        }
    ]
}
    ''';

    Event event = eventFromJson(responseString);

    for (int i = 0; i < event.data.length; i++) {
      mapFetch[event.data[i].date] = [event.data[i].title];
    }

    return mapFetch;
  }

working demo

full code

import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
// To parse this JSON data, do
//
//     final event = eventFromJson(jsonString);

import 'dart:convert';

Event eventFromJson(String str) => Event.fromJson(json.decode(str));

String eventToJson(Event data) => json.encode(data.toJson());

class Event {
  String error;
  String message;
  List<Datum> data;

  Event({
    this.error,
    this.message,
    this.data,
  });

  factory Event.fromJson(Map<String, dynamic> json) => Event(
        error: json["error"],
        message: json["message"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "error": error,
        "message": message,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  bool status;
  String id;
  String groupId;
  DateTime date;
  String title;
  int priority;
  String description;
  List<dynamic> tasks;
  DateTime createdDate;
  int v;

  Datum({
    this.status,
    this.id,
    this.groupId,
    this.date,
    this.title,
    this.priority,
    this.description,
    this.tasks,
    this.createdDate,
    this.v,
  });

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        status: json["status"],
        id: json["_id"],
        groupId: json["group_id"],
        date: DateTime.parse(json["date"]),
        title: json["title"],
        priority: json["priority"],
        description: json["description"],
        tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
        createdDate: DateTime.parse(json["created_date"]),
        v: json["__v"],
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "_id": id,
        "group_id": groupId,
        "date": date.toIso8601String(),
        "title": title,
        "priority": priority,
        "description": description,
        "tasks": List<dynamic>.from(tasks.map((x) => x)),
        "created_date": createdDate.toIso8601String(),
        "__v": v,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      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> with TickerProviderStateMixin {
  List _selectedEvents;
  int _counter = 0;
  Map<DateTime, List> _events;
  CalendarController _calendarController;
  AnimationController _animationController;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<Map<DateTime, List>> getTask() async {
    Map<DateTime, List> mapFetch = {};

    await Future.delayed(const Duration(seconds: 3), () {});

    /*String link = baseURL + fetchTodoByDate;
    var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    if (res.statusCode == 200) {
      // need help in creating fetch logic here
    }*/

    String responseString = '''
    {
    "error": "0",
    "message": "Got it!",
    "data": [
        {
            "status": false,
            "_id": "5e04a27692928701258b9b06",
            "group_id": "5df8aaae2f85481f6e31db59",
            "date": "2019-12-29T00:00:00.000Z",
            "title": "new task",
            "priority": 5,
            "description": "just a description",
            "tasks": [],
            "created_date": "2019-12-26T12:07:18.301Z",
            "__v": 0
        },
        {
            "status": false,
            "_id": "5e04a27692928701258b9b06",
            "group_id": "5df8aaae2f85481f6e31db59",
            "date": "2019-12-30T00:00:00.000Z",
            "title": "abc",
            "priority": 5,
            "description": "just a description",
            "tasks": [],
            "created_date": "2019-12-26T12:07:18.301Z",
            "__v": 0
        }
    ]
}
    ''';

    Event event = eventFromJson(responseString);

    for (int i = 0; i < event.data.length; i++) {
      mapFetch[event.data[i].date] = [event.data[i].title];
    }

    return mapFetch;
  }

  void _onDaySelected(DateTime day, List events) {
    print('CALLBACK: _onDaySelected');
    setState(() {
      _selectedEvents = events;
    });
  }

  @override
  void initState() {
    final _selectedDay = DateTime.now();
    _selectedEvents = [];
    _calendarController = CalendarController();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );

    _animationController.forward();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getTask().then((val) => setState(() {
            _events = val;
          }));
      //print( ' ${_events.toString()} ');
    });
    super.initState();
  }

  @override
  void dispose() {
    _calendarController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _buildTableCalendarWithBuilders(),
            const SizedBox(height: 8.0),
            const SizedBox(height: 8.0),
            Expanded(child: _buildEventList()),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _buildTableCalendarWithBuilders() {
    return TableCalendar(
      //locale: 'pl_PL',
      calendarController: _calendarController,
      events: _events,
      //holidays: _holidays,
      initialCalendarFormat: CalendarFormat.month,
      formatAnimation: FormatAnimation.slide,
      startingDayOfWeek: StartingDayOfWeek.sunday,
      availableGestures: AvailableGestures.all,
      availableCalendarFormats: const {
        CalendarFormat.month: '',
        CalendarFormat.week: '',
      },
      calendarStyle: CalendarStyle(
        outsideDaysVisible: false,
        weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
        holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
      ),
      daysOfWeekStyle: DaysOfWeekStyle(
        weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
      ),
      headerStyle: HeaderStyle(
        centerHeaderTitle: true,
        formatButtonVisible: false,
      ),
      builders: CalendarBuilders(
        selectedDayBuilder: (context, date, _) {
          return FadeTransition(
            opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
            child: Container(
              margin: const EdgeInsets.all(4.0),
              padding: const EdgeInsets.only(top: 5.0, left: 6.0),
              color: Colors.deepOrange[300],
              width: 100,
              height: 100,
              child: Text(
                '${date.day}',
                style: TextStyle().copyWith(fontSize: 16.0),
              ),
            ),
          );
        },
        todayDayBuilder: (context, date, _) {
          return Container(
            margin: const EdgeInsets.all(4.0),
            padding: const EdgeInsets.only(top: 5.0, left: 6.0),
            color: Colors.amber[400],
            width: 100,
            height: 100,
            child: Text(
              '${date.day}',
              style: TextStyle().copyWith(fontSize: 16.0),
            ),
          );
        },
        markersBuilder: (context, date, events, holidays) {
          final children = <Widget>[];

          if (events.isNotEmpty) {
            children.add(
              Positioned(
                right: 1,
                bottom: 1,
                child: _buildEventsMarker(date, events),
              ),
            );
          }

          if (holidays.isNotEmpty) {
            children.add(
              Positioned(
                right: -2,
                top: -2,
                child: _buildHolidaysMarker(),
              ),
            );
          }

          return children;
        },
      ),
      onDaySelected: (date, events) {
        _onDaySelected(date, events);
        _animationController.forward(from: 0.0);
      },
      onVisibleDaysChanged: _onVisibleDaysChanged,
    );
  }

  void _onVisibleDaysChanged(
      DateTime first, DateTime last, CalendarFormat format) {
    print('CALLBACK: _onVisibleDaysChanged');
  }

  Widget _buildEventsMarker(DateTime date, List events) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        color: _calendarController.isSelected(date)
            ? Colors.brown[500]
            : _calendarController.isToday(date)
                ? Colors.brown[300]
                : Colors.blue[400],
      ),
      width: 16.0,
      height: 16.0,
      child: Center(
        child: Text(
          '${events.length}',
          style: TextStyle().copyWith(
            color: Colors.white,
            fontSize: 12.0,
          ),
        ),
      ),
    );
  }

  Widget _buildHolidaysMarker() {
    return Icon(
      Icons.add_box,
      size: 20.0,
      color: Colors.blueGrey[800],
    );
  }

  Widget _buildEventList() {
    return ListView(
      children: _selectedEvents
          .map((event) => Container(
                decoration: BoxDecoration(
                  border: Border.all(width: 0.8),
                  borderRadius: BorderRadius.circular(12.0),
                ),
                margin:
                    const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                child: ListTile(
                  title: Text(event.toString()),
                  onTap: () => print('$event tapped!'),
                ),
              ))
          .toList(),
    );
  }
}

这篇关于如何获取日历的地图列表?[扑]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆