dart 使用Map列表选择/取消选择时隙的特定网格

6yjfywim  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(88)

我的任务是创建时间段。我尝试从GridView中选择grid(实际上想改变颜色),并取消选择所有其他网格。我使用MapList来实现,但是这个List需要常量值(总插槽数)。是否可以传递计算插槽总数的变量?如果没有,我该如何应对这个问题?下面是我的代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:intl/intl.dart';

late String appointmentTime;

class test2 extends StatefulWidget {
  const test2({Key? key}) : super(key: key);

  @override
  State<test2> createState() => _test2State();
}

class _test2State extends State<test2> {

  String hospitalAddress = "";
  String hospitalContact = "";

  Future <String> getHospitalDocId2(hospitalCheck) async {
    await FirebaseFirestore.instance.collection("HopitalData").where("Hospital Name", isEqualTo: hospitalCheck).get().then((querySnapshot) {
      for (var docSnapshot in querySnapshot.docs) {
        // print('${docSnapshot.id} => ${docSnapshot.data()}');
        hospitalAddress = docSnapshot["Hospital Address"];
        hospitalContact = docSnapshot["Hospital Contact"];
        return "";
      }
    },
      onError: (e) => print("Error completing: $e"),
    );
    return "";
  }
  
  final List<bool> _selectedTime = List.generate(7, (index) => false); // Fill it with false initially

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Book Your Slot'),
      ),
      body: StreamBuilder(
          stream: FirebaseFirestore.instance.collection('DoctorAll').doc("${Get.arguments['documentID'].toString()}").snapshots(),
          builder: (context, snapshots) {
            if (!snapshots.hasData) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }
            var doctorDocument = snapshots.data;
            var documentID = doctorDocument!.id;
            getHospitalDocId2(doctorDocument!["Doctor In-Clinic Hospital "]);

            return Container(
              padding: const EdgeInsets.all(15.0),
              child: Column(
                children: [

                  const SizedBox(height: 10.0),

                  // Doctor Info
                  Container(
                    width: MediaQuery.of(context).size.width,
                    padding: const EdgeInsets.all(20.0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.3),
                          spreadRadius: 2,
                          blurRadius: 5,
                          offset: const Offset(0, 2), // changes position of shadow
                        ),
                      ],
                    ),

                    child: Column(
                      children: <Widget>[

                        // Doctor Image
                        CircleAvatar(
                          radius: 50.0,
                          backgroundImage: NetworkImage(
                              doctorDocument!["pic"] ?? 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dXNlcnxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
                        ),

                        const SizedBox(height: 10.0),

                        // Doctor Name
                        Text(
                          // doctorDocument?.id,
                          doctorDocument!["Doctor Name"] ?? '',
                          textAlign: TextAlign.center,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 20.0,
                          ),
                        ),

                        const SizedBox(height: 5.0),

                        // Doctor Speciality
                        Text(
                          doctorDocument!["Doctor Specialization"] ?? '',
                          style: TextStyle(
                            fontSize: 16.0,
                            color: Colors.grey[600],
                          ),
                        ),

                        const SizedBox(height: 5.0),

                        // Doctor Hospital
                        Text(
                          doctorDocument!["Doctor In-Clinic Hospital "] ?? '',
                          // 'Doctors Hospital, Lahore',
                          textAlign: TextAlign.center,
                          maxLines: 5,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 16.0,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 30.0),

                  // 2 in rows (hospital & fee)
                  SizedBox(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // selected hospital name
                        Text(
                          doctorDocument!["Doctor In-Clinic Hospital "] ?? '',
                          style: const TextStyle(
                            color: Colors.blueAccent,
                            fontSize: 15.0,
                          ),
                        ),

                        // Fee 4 selected appointment
                        Text(
                            'Fee: Rs '+ doctorDocument!["Doctor In-Clinic Fee"] +''
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 10.0),

                  //Time Slot gridview (Incomplete)
                  Container(
                    child: const Text(
                      'Select Time: ',
                      style: TextStyle(
                        // color: Colors.blueAccent,
                        fontSize: 15.0,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Center(
                      child: TimeSlotsWidget(
                        startTime: DateFormat('HH:mm').format(DateFormat('hh:mm aaa').parse(doctorDocument!["Doctor STime In-Clinic"])),
                        endTime: DateFormat('HH:mm').format(DateFormat('hh:mm aaa').parse(doctorDocument!["Doctor ETime In-Clinic"])),

                      ),
                    ),
                  ),

                  const SizedBox(height: 10.0),

                  ElevatedButton(
                    style: TextButton.styleFrom(
                      backgroundColor: Colors.blue, // Background Color
                    ),
                    child: const Text(
                      'Book Appointment',
                      //style: TextStyle(fontSize: 24),
                    ),
                    onPressed: () {
                      Navigator.of(context).pushNamed('/patientAppointmentConfirmPage',
                          arguments: {
                            'documentID': documentID,
                            'appointmentTime': appointmentTime,
                            'hospitalAddress': hospitalAddress,
                            'hospitalContact': hospitalContact,

                          }
                      );
                      // Navigate to In-clinic Checkup page
                    },

                  )
                ],
              ),
            );
          }
      ),
    );
  }
}

class TimeSlotsWidget extends StatefulWidget {
  final String startTime;
  final String endTime;

  TimeSlotsWidget({ required this.startTime, required this.endTime});

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

class _TimeSlotsWidgetState extends State<TimeSlotsWidget> {

  @override
  void initState() {
    super.initState();
    _timeSlots = _getTimeSlots(widget.startTime, widget.endTime);
    totalSlots = _getTotalSlots(widget.startTime, widget.endTime);

  }

  List<String> _timeSlots = [];
  int totalSlots = 0;
  final List<bool> _selectedTime = List.generate(totalSlots, (index) => false); // Fill it with false initially
  
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: GridView.count(
            crossAxisCount: 4,
            crossAxisSpacing: 20,
            mainAxisSpacing: 20,
            padding: const EdgeInsets.all(20.0),
            children: _timeSlots.map((time) => TextButton(
              onPressed: () {
                TextButton.styleFrom(foregroundColor: Colors.greenAccent);
                // String new1 =  DateFormat.jm("h:mma").format('10:00').toString();
                // DateTime parsedTime = DateFormat('HH:mm').parse(time);
                String formattedTime = DateFormat('hh:mm aaa').format(DateFormat('HH:mm').parse(time));
                print(formattedTime);
                appointmentTime = formattedTime;
              },
              child: Text(DateFormat('hh:mm aaa').format(DateFormat('HH:mm').parse(time))),
              style: TextButton.styleFrom(
                primary: Colors.blueAccent,
                //backgroundColor: Colors.blue,
                padding: const EdgeInsets.symmetric(
                  horizontal: 2,
                  vertical: 2,
                ),
                shape: RoundedRectangleBorder(
                  side: const BorderSide(color: Colors.blueAccent),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ))
                .toList(),
          ),
        ),
      ],
    );
  }

  List<String> _getTimeSlots(String startTime, String endTime) {
    final List<String> timeSlots = [];
    DateTime start = DateTime.parse('2022-01-01 $startTime');
    DateTime end = DateTime.parse('2022-01-01 $endTime');
    int val = 0;

    while (start.isBefore(end)) {
      val++;
      timeSlots.add(start.toString().substring(11, 16));
      start = start.add(const Duration(minutes: 30));
    }

    return timeSlots;
  }

  int _getTotalSlots(String startTime, String endTime) {
    final List<String> timeSlots = [];
    DateTime start = DateTime.parse('2022-01-01 $startTime');
    DateTime end = DateTime.parse('2022-01-01 $endTime');
    int val = 0;

    while (start.isBefore(end)) {
      val++;
      timeSlots.add(start.toString().substring(11, 16));
      start = start.add(const Duration(minutes: 30));
    }

    return val;
  }
}

字符串
我想预约。选择时,插槽的颜色应与其他插槽不同。

lyr7nygr

lyr7nygr1#

尝试将_selectedTime定义移动到init状态中。示例如下:

class _TimeSlotsWidgetState extends State<TimeSlotsWidget> {
  late List<String> _timeSlots;
  late List<bool> _selectedTime;
  late int totalSlots;

  @override
  void initState() {
    super.initState();
    totalSlots = _getTotalSlots(widget.startTime, widget.endTime);
    _timeSlots = _getTimeSlots(widget.startTime, widget.endTime);
    _selectedTime = List<bool>.generate(totalSlots, (index) => false);
  }
//Your remaining code goes here
}

字符串
希望这能帮上忙

相关问题