【问题标题】:Show time with a 0 in front of it if it is less than 10如果小于 10,则在其前面显示 0
【发布时间】:2021-05-07 03:00:01
【问题描述】:
import 'package:flutter/material.dart';

class Time extends StatefulWidget {
  @override
  _TimeState createState() => _TimeState();
}

class _TimeState extends State<Time> {
  String time = "Press Button to see time";
  bool isSelected = false;
  @override
  Widget build(BuildContext context) {
    TimeOfDay startTime = TimeOfDay(hour: 01, minute: 00);
    final endTime = TimeOfDay(hour: 23, minute: 59);
    final step = Duration(minutes: 5);

    Iterable<TimeOfDay> getTimes(
        TimeOfDay startTime, TimeOfDay endTime, Duration step) sync* {
      var hour = startTime.hour;
      var minute = startTime.minute;

      do {
        yield TimeOfDay(hour: hour, minute: minute);
        minute += step.inMinutes;
        while (minute >= 60) {
          minute -= 60;
          hour++;
        }
      } while (hour < endTime.hour ||
          (hour == endTime.hour && minute <= endTime.minute));
    }

    final times = getTimes(startTime, endTime, step)
        .where((t) =>
            t.minute >= TimeOfDay.now().minute &&
            t.hour >= TimeOfDay.now().hour)
        .map((tod) => tod.format(context));

    return Scaffold(
      body: SafeArea(
        child: Container(
          width: MediaQuery.of(context).size.width,
          child: Wrap(
            direction: Axis.horizontal,
            children: times
                .map<Widget>(
                  (t) => GestureDetector(
                    onTap: () {
                      setState(() {
                        isSelected = !isSelected;
                      });
                    },
                    child: Container(
                      margin: EdgeInsets.all(10.0),
                      decoration: BoxDecoration(
                          color: isSelected ? Colors.deepOrange : Colors.white,
                          border: Border.all(
                            color: Colors.deepOrange,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(
                            10.0,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: isSelected ? Colors.black26 : Colors.white,
                              blurRadius: 5,
                              offset: Offset(2, 2),
                            )
                          ]),
                      padding: EdgeInsets.all(10.0),
                      child: Text(
                        t,
                        style: TextStyle(
                          color: isSelected ? Colors.white : Colors.deepOrange,
                        ),
                      ),
                    ),
                  ),
                )
                .toList(),
          ),
        ),
      ),
    );
  }
}

我想问一下,如果现在时间不到 10 点,比如说 9:30。它正在显示它,因为它不是我正在寻找的 09:30。你能告诉我怎么做吗?此外,如果我点击任何一个容器,它们都会被选中。我如何获得它,以便只有用户按下的容器被选中。我怎么知道用户选择了哪一个你能帮我解决这个问题吗

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    目前如果时间不到 10 点,比如说 9:30。它正在显示它,因为它不是我正在寻找的 09:30。

    尝试改变

    .map((tod) => tod.format(context));
    

    .map((tod) => "${tod.hour}".padLeft(2, '0') + ':' + "${tod.minute}".padLeft(2, '0'));
    // Pad '0' left to the hours and minutes until both has two characters and join with ':'
    

    如果你想依赖tod.format(context)实现,也可以试试

    .map((tod) => tod.format(context).padLeft(5, '0'));
    // If it returns "5:40", pad '0' left until this string has five characters ("05:40")
    

    此外,如果我点击任何一个容器,它们都会被选中。我怎样才能让只有我按下的容器被选中。

    您可以将isSelected 替换为跟踪选择了哪些容器的列表:

    List<bool> selectedTimes;
    

    每次设置times,同时设置selectedTimes

    final times = getTimes(startTime, endTime, step)
        .where((t) =>
            t.minute >= TimeOfDay.now().minute &&
            t.hour >= TimeOfDay.now().hour)
        .map((tod) => tod.format(context));
    
    // Start all containers unselected
    selectedTimes = times.map((t) => false).toList();
    

    然后,在您使用isSelected 的地方,替换为在selectedTimes 中获取相应的时间索引。您可以通过创建一个新方法来执行此操作,在该方法中返回一个新的Container

    Widget buildTimeTile(BuildContext context, List<String> times, int i) {
      final t = times[i];
      return GestureDetector(
        onTap: () {
          setState(() {
            selectedTimes[i] = !selectedTimes[i];
          });
        },
        child: Container(
          // ...
        )
      );
    }
    

    现在,在您创建 Container 的位置,替换为使用 for 循环的方法调用:

    Wrap(
      direction: Axis.horizontal,
      children: [
        for (int i = 0; i < times.length; i++)
          buildTimeTile(context, times, i)
      ]
    );
    

    完整代码:

    class Time extends StatefulWidget {
      @override
      _TimeState createState() => _TimeState();
    }
    
    class _TimeState extends State<Time> {
      List<String> times;
      List<bool> selectedTimes;
      String time = "Press Button to see time";
      
      void initTimes() {
        TimeOfDay startTime = TimeOfDay(hour: 00, minute: 00);
        final endTime = TimeOfDay(hour: 23, minute: 59);
        final step = Duration(minutes: 5);
       
        times = getTimes(startTime, endTime, step)
            .where((t) =>
                t.hour > TimeOfDay.now().hour ||
                (t.hour >= TimeOfDay.now().hour &&
                    t.minute > TimeOfDay.now().minute))
            .map((tod) => tod.format(context).padLeft(8, '0'),)
            .toList();
       
        selectedTimes = times.map((t) => false).toList();
      }
     
      Iterable<TimeOfDay> getTimes(
        TimeOfDay startTime, TimeOfDay endTime, Duration step) sync* {
          var hour = startTime.hour;
          var minute = startTime.minute;
    
          do {
            yield TimeOfDay(hour: hour, minute: minute);
            minute += step.inMinutes;
            while (minute >= 60) {
              minute -= 60;
              hour++;
            }
          } while (hour < endTime.hour ||
              (hour == endTime.hour && minute <= endTime.minute));
        }
     
      Widget buildTimeTile(BuildContext context, int i) {
          final t = times[i];
          return GestureDetector(
            onTap: () {
              setState(() {
                selectedTimes[i] = !selectedTimes[i];
              });
            },
            child: Container(
              margin: EdgeInsets.all(7.5),
              decoration: BoxDecoration(
                color: selectedTimes[i] ? Colors.deepOrange : Colors.white,
                border: Border.all(
                  color: Colors.deepOrange,
                  width: 1,
                ),
                borderRadius: BorderRadius.circular(
                  10.0,
                ),
              ),
              padding: EdgeInsets.all(10.0),
              child: Text(
                t,
                style: TextStyle(
                  color: selectedTimes[i] ? Colors.white : Colors.black,
                ),
              ),
            ),
          );
        }
     
      @override
      Widget build(BuildContext context) {
        if (times == null) initTimes();
        return Wrap(
          direction: Axis.horizontal,
          children: [
            for (int i = 0; i < times.length; i++) buildTimeTile(context, i)
          ],
        );
      }
    }
    

    【讨论】:

    • 感谢您的成功。你能不能看看问题的第二部分?我真的很感激。
    • 谢谢,我已经编辑了我的答案。看看这是否能解决您的问题。
    • 好的,所以它有点像我的意思是它显示了我在将其打印到控制台时选择的时间。它也在更新 selectedtimes 列表,但问题是它没有在 UI 中显示任何更新。你能告诉我你的电子邮件或任何我可以联系到你的地方并发送这个更新的代码,以便你寻找问题。
    • 无论哪种方式,如果它可以帮助其他人解决同样的问题,我已经将完整的代码添加到答案中。
    • 完整的代码似乎有我提到的同样的问题。它没有在 UI 中更新。我通过您要求的邮件将代码邮寄给您
    【解决方案2】:

    做了一些改动。这应该可以完美地工作。感谢@Chris 的指导

    import 'package:flutter/material.dart';
    
    class Time extends StatefulWidget {
    
      @override
      _TimeState createState() => _TimeState();
    }
    
    class _TimeState extends State<Time> {
      String time = "Press Button to see time";
      String _selectedTime;  // ADDED VARIABLE TO SAVE SELECTED TIME
      @override
      Widget build(BuildContext context) {
        TimeOfDay startTime = TimeOfDay(hour: 01, minute: 00);
        final endTime = TimeOfDay(hour: 23, minute: 59);
        final step = Duration(minutes: 5);
    
        String _time(int digit) {
          if(digit < 10) {
            return '0$digit';
          } else {
            return '$digit';
          }
        }
    
        Iterable<TimeOfDay> getTimes(
            TimeOfDay startTime, TimeOfDay endTime, Duration step) sync* {
          var hour = startTime.hour;
          var minute = startTime.minute;
    
          do {
            yield TimeOfDay(hour: hour, minute: minute);
            minute += step.inMinutes;
            while (minute >= 60) {
              minute -= 60;
              hour++;
            }
          } while (hour < endTime.hour ||
              (hour == endTime.hour && minute <= endTime.minute));
        }
    
        final times = getTimes(startTime, endTime, step)
            .where((t) {
          return (t.hour <= TimeOfDay.now().hour
            ? t.minute >= TimeOfDay.now().minute
            : t.minute == t.minute)
          && t.hour >= TimeOfDay.now().hour;
        }
        ).map((tod)  {return '${_time(tod.hour)}:${_time(tod.minute)} ${tod.hour >= 12 ? "PM" : "AM" }'; });
    
        return Scaffold(
          body: SafeArea(
            child: Container(
              width: MediaQuery.of(context).size.width,
              child: Wrap(
                direction: Axis.horizontal,
                children: times
                    .map<Widget>(
                      (t) => GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedTime = t;
                      });
                    },
                    child: Container(
                      margin: EdgeInsets.all(10.0),
                      decoration: BoxDecoration(
                          color: t == _selectedTime ? Colors.deepOrange : Colors.white,  // CHANGED HERE
                          border: Border.all(
                            color: Colors.deepOrange,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(
                            10.0,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: t == _selectedTime ? Colors.black26 : Colors.white,  // CHANGED HERE
                              blurRadius: 5,
                              offset: Offset(2, 2),
                            )
                          ]),
                      padding: EdgeInsets.all(10.0),
                      child: Text(
                        t,
                        style: TextStyle(
                          color: t == _selectedTime ? Colors.white : Colors.deepOrange,  // CHANGED HERE
                        ),
                      ),
                    ),
                  ),
                )
                    .toList(),
              ),
            ),
          ),
        );  }
    }
    

    【讨论】:

    • 我在哪里添加这个?
    • 欢迎来到 Stack Overflow。请阅读How to Answer
    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多