Как напечатать несколько значений из списка Dynami c в цикле ... - PullRequest
0 голосов
/ 04 апреля 2020

Hy, я работаю над проектом, использую плагин table_calendar. Я получаю записи о собраниях из базы данных и показываю их в виде маркера в календаре. Теперь я хочу показать детали этого собрания на странице в списке, но я не Я имею представление о том, как это сделать, я могу распечатать его идентификаторы собраний в списке, но как я могу распечатать другие сведения о собраниях, такие как место, время, имя клиента и т. д. c?

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);
          },
        )
      ],
    );
  }
}

чего я достиг? enter image description here

Чего я хочу достичь enter image description here

...