如何在...循环中从动态列表中打印多个值

Posted

技术标签:

【中文标题】如何在...循环中从动态列表中打印多个值【英文标题】:How to print multiple values from dynamic list in ... loop 【发布时间】:2020-07-16 19:17:06 【问题描述】:

嘿,我正在做一个项目,使用 table_calendar 插件我从数据库接收会议记录并将它们显示为日历上的标记,现在我想在列表中的页面上显示会议详细信息,但我不知道怎么做吗,我可以在列表中打印会议 ID,但是我如何打印其他会议详细信息,例如位置、时间、客户姓名等?

import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'notifcation_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:table_calendar/table_calendar.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'variables.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:expandable/expandable.dart';

TextEditingController agendaController = new TextEditingController();
TextEditingController phoneController = new TextEditingController();
TextEditingController locationController = new TextEditingController();
meeting mee = new meeting();
meeting meet = new meeting();
String _time = '';
List meetDate;
CalendarController _controller;

String dateWithT;

String emailFromSharedPref, meetingAdded;
Map smData;
Map meetingDetail;
List meetingInfo, customerInfo;

List<dynamic> _selectedEvents;
Map<DateTime, List<dynamic>> _events;
Map<DateTime, List<dynamic>> c_nameMap;

class AddMeeting extends StatefulWidget 
  @override
  _AddMeetingeState createState() => _AddMeetingeState();


class _AddMeetingeState extends State<AddMeeting> 
  @override
  void initState() 
    super.initState();
    _controller = CalendarController();

    _events = ;
    _selectedEvents = [];
    c_nameMap = ;
    getIdAndGetMeetings();
  

  Future getIdAndGetMeetings() async 
    // getting email from SharedPreferences
    SharedPreferences prefs = await SharedPreferences.getInstance();
    emailFromSharedPref = prefs.getString('email');
    // getting saleManager info using email
    var url = "http://.../getSaleMangerDetal.php";
    var response = await http.post(url, body: 
      "m_email": emailFromSharedPref,
    );
    smData = jsonDecode(response.body);
    // getting customer info using saleManagerID
    var customerInfoUrl = "http://.../calender/getCustomerInfo.php";
    var customerInfoResponse = await http.post(customerInfoUrl, body: 
      "sm_id": smData['manager_id'],
    );
    // saving customer info in the list, because there are many dict in the list
    customerInfo = jsonDecode(customerInfoResponse.body);

    // get meetings details from server using saleManager Id
    var getmeetingUrl = "http://.../getMeetings.php";
    var getMeetiongResponse = await http.post(getmeetingUrl, body: 
      "manager_id": smData['manager_id'],
    );
    meetingInfo = jsonDecode(getMeetiongResponse.body);
    print(meetingInfo);
    for (int i = 0; i < meetingInfo.length; i++) 
      dateWithT =
          meetingInfo[i]['m_date'].replaceAll(new RegExp(r'[^\w\s]+'), '');
      dateWithT = dateWithT.replaceAll(' ', '');
      dateWithT = dateWithT + "000000";
      dateWithT = dateWithT.substring(0, 8) + 'T' + dateWithT.substring(8);
      mee.dateTime = DateTime.parse(dateWithT);
      if (_events[mee.dateTime] != null) 
        _events[mee.dateTime].add(meetingInfo[i]['meeting_id']);
       else 
        _events[mee.dateTime] = [meetingInfo[i]['meeting_id']];
      
    
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Calendar'),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // Text(_time),
            TableCalendar(
              events: _events,
              // initialCalendarFormat: CalendarFormat.week,
              calendarStyle: CalendarStyle(
                  canEventMarkersOverflow: true,
                  todayColor: Colors.orange,
                  selectedColor: Theme.of(context).primaryColor,
                  todayStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18.0,
                      color: Colors.white)),
              headerStyle: HeaderStyle(
                centerHeaderTitle: true,
                formatButtonDecoration: BoxDecoration(
                  color: Colors.orange,
                  borderRadius: BorderRadius.circular(20.0),
                ),
                formatButtonTextStyle: TextStyle(color: Colors.white),
                formatButtonShowsNext: false,
              ),
              startingDayOfWeek: StartingDayOfWeek.monday,
              onDaySelected: (date, events) 
                setState(() 
                  _selectedEvents = events;
                );
              ,
              builders: CalendarBuilders(

              calendarController: _controller,
            ),

            ..._selectedEvents.map((event) => Stack(
                  children: <Widget>[
                    // getMeetingsIndividualDetails(event),
                    Card(
                      child: Container(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: ExpandablePanel(
                            header: Text(event),

                            // Text(getMeetingsIndividualDetails(event, 'c_name')),
                            collapsed: Text(
                              'qwe',
                              softWrap: true,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                            expanded: Text(
                              'as',
                              softWrap: true,
                            ),
                            tapHeaderToExpand: true,
                            hasIcon: true,
                          ),
                        ),
                      ),
                    ),
                  ],
                )),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _showAddDialog,
      ),
    );
  

  _showAddDialog() async 
    await showDialog(
        context: context,
        builder: (context) => StatefulBuilder(builder: (context, setState) 
              return ShowDialog();
            ));
    setState(() 
      _selectedEvents = _events[mee.dateTime];
    );
  


addMeetingToDatabase(List meetDate2) async 
  // print(meetDate2[0]);
  var getmeetingUrls = "http://.../addMeeting.php";
  var getMeetiongResponses = await http.post(getmeetingUrls, body: 
    "sm_id": smData['manager_id'],
    "c_id": '2',
    "agenda": agendaController.text,
    "phone": phoneController.text,
    "location": locationController.text,
    "date": meetDate2[0],
    "time": _time,
  );
  meetingAdded = jsonDecode(getMeetiongResponses.body);
  print(meetingAdded);



class ShowDialog extends StatefulWidget 
  @override
  _ShowDialogState createState() => _ShowDialogState();


class _ShowDialogState extends State<ShowDialog> 
  @override
  Widget build(BuildContext context) 
    return AlertDialog(
      content: SingleChildScrollView(
        child: Container(
          // height: MediaQuery.of(context).size.height/3,
          child: Column(
            // mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(top: 8.0, bottom: 8),
                child: TextField(
                  controller: phoneController,
                  // maxLines: null,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Phone',
                      prefixIcon: Icon(Icons.phone_android),
                      labelStyle: TextStyle(fontSize: 15)),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 8.0, bottom: 8),
                child: TextField(
                  controller: locationController,
                  // maxLines: null,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Meeting Location',
                      prefixIcon: Icon(Icons.add_location),
                      labelStyle: TextStyle(fontSize: 15)),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 8.0, bottom: 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    RaisedButton(
                        child: Text('Meeting Time'),
                        onPressed: () 
                          DatePicker.showTimePicker(context,
                              theme: DatePickerTheme(
                                containerHeight: 210.0,
                              ),
                              showTitleActions: true, onConfirm: (time) 
                            print('confirm $time');
                            _time =
                                '$time.hour : $time.minute : $time.second';
                            setState(() );
                          ,
                              currentTime: DateTime.now(),
                              locale: LocaleType.en);
                          setState(() );
                        ),
                    Text(_time)
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 8.0, bottom: 8),
                child: TextField(
                  controller: agendaController,
                  maxLines: null,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Agenda',
                      prefixIcon: Icon(Icons.message),
                      labelStyle: TextStyle(fontSize: 15)),
                ),
              ),
            ],
          ),
        ),
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("Save"),
          onPressed: () 
            // if (agendaController.text.isEmpty) return;
            // if (_events[_controller.selectedDay] != null) 
            //   _events[_controller.selectedDay]
            //       .add(agendaController.text);
            String asd = _controller.selectedDay.toString();
            meetDate = asd.split(' ');
            addMeetingToDatabase(meetDate);

            agendaController.clear();
            phoneController.clear();
            locationController.clear();
            Navigator.pop(context);
          ,
        )
      ],
    );
  

我取得了什么成就?

我想要达到的目标

【问题讨论】:

【参考方案1】:

而不是List&lt;Dynamic&gt;,最好将这些数据映射到一个对象上,以便可以使用常量getter 函数访问它。

Map&lt;DateTime, List&lt;dynamic&gt;&gt; _events; 成为Map&lt;DateTime, EventDetails&gt; _events;

其中 EventDetails 包含例如:

class EventDetails 
  String author;
  String eventName;
  String description;

  EventDetails(
      required this.author,
        required this.eventName,
        required this.description);

然后您可以使用对象添加数据。

EventDetails eventDetails = EventDetails(author: 'AUTHOR', 
    eventName: 'EVENT_NAME', description: 'DESCRIPTION');

...

_events[mee.dateTime].add(eventDetails);

【讨论】:

以上是关于如何在...循环中从动态列表中打印多个值的主要内容,如果未能解决你的问题,请参考以下文章

将 for 循环中的多个打印输出值存储到列表或变量中

如何从c#中循环动态列表中获取所有值?

如何在 php foreach 循环中从 json obj 获取值

如何在自动生成的for循环中从html表单中获取唯一值

java - 如何在Java中从MySQL结果集中的while循环中添加值?

如何在flutter中从API创建多个复选框