Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of increasing dates in flutter?

I am trying to create a list of 60 dates that increases by one day, each item, starting from the current date in flutter. But it isn't working it just stays on the current date.

My code:

import 'package:flutter/material.dart';

class UpComingPage extends StatefulWidget {
  UpComingPage({Key key}) : super(key: key);

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

class _UpComingPageState extends State<UpComingPage> {
  @override
  Widget build(BuildContext context) {
    final items = List<DateTime>.generate(60, (i) {
      DateTime date = DateTime.utc(
        DateTime.now().year,
        DateTime.now().month,
        DateTime.now().day,
      );

      date.add(Duration(days: i));

      return date;
    });

    return CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          title: Text('Title'),
          centerTitle: true,
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              return ListTile(
                title: Text('${items[index]}'),
              );
            },
            childCount: items.length,
          ),
        ),
      ],
    );
  }
}
like image 822
Luke Leppan Avatar asked Jan 26 '23 11:01

Luke Leppan


1 Answers

You should be returning date.add(Duration(days: i)) since the DateTime.add method doesn't actually modify the instance, but instead returns a new one with the changes made.

    final items = List<DateTime>.generate(60, (i) =>
      DateTime.utc(
        DateTime.now().year,
        DateTime.now().month,
        DateTime.now().day,
      ).add(Duration(days: i)));
like image 129
Ben Konyi Avatar answered Jan 28 '23 00:01

Ben Konyi