【问题标题】:Using an algorithm to generate days in a month使用算法生成一个月中的天数
【发布时间】:2021-04-09 08:39:10
【问题描述】:

我对 Flutter 和编程很陌生,我正在做这个迷你项目,但我被困住了。

我已经创建了一年中月份的列表,我想在用户点击一个月时生成相应月份的天数。

我生成日子的想法很简单。当我创建月份列表时,我使用了一个类和构造函数。此构造函数将询问月份和月份的编号。一月有数字“1”,二月有“2”到十二月有“12”

所以我计划创建一个从 1 到 31(一个月中的天数)计数的 for 循环。根据与月份相关的数字,它将计数到 28,30 或 31。因此,如果用户在 1 月点击,它必须计数到 31 天并生成天数列表,如果是 2 月则为 28 天。

正如您从我的代码中看到的那样,我已经减少了月份部分,但是生成日期是一个问题。


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: home(), title: 'Flutter Demo', theme: ThemeData());
  }
}

class home extends StatefulWidget {
  @override
  _homeState createState() => _homeState();
}

class _homeState extends State<home> {
  List<months> monthoftheyear = [
    months(month: "January", id: 1),
    months(month: "February", id: 2),
    months(month: "March", id: 3),
    months(month: "April", id: 4),
    months(month: "May", id: 5),
    months(month: "June", id: 6),
    months(month: "July", id: 7),
    months(month: "August", id: 8),
    months(month: "September", id: 9),
    months(month: "October", id: 10),
    months(month: "November", id: 11),
    months(month: "December", id: 12),
  ];

  Widget monthtemp(display) {
    return FlatButton(
      child: Card(
        child: Text(display.month),
        margin: EdgeInsets.all(20),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
            children:
                monthoftheyear.map((display) => monthtemp(display)).toList()),
      ),
    );
  }
}



for (int i = 0; i>= 31; i++);

如果(月份 id 为 1,那么 for 循环应该数到 31 并将其放入卡片中, 如果它是 2 月,那么它应该数到 28 等)

【问题讨论】:

  • 你能修正代码的缩进吗?
  • This post 按月计算可能会对您有所帮助。
  • 不是 29 天?你住在没有闰日的地方吗?

标签: flutter dart


【解决方案1】:

随意使用搜索功能:This thread已经提供了一些部分解决方案。我认为这样的事情应该可行:

// look up number of days for this month in a small lookup table
var nrOfDays = ...;

// generate a list with all days
var days = Iterable<int>.generate(nrOfDays + 1).skip(1).toList();

// do something with your days to display them
var displayedDays = days.map((day) => ...);

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 2017-10-22
    • 2012-01-08
    • 1970-01-01
    • 2014-05-08
    • 2022-11-24
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多