Home > OS >  Dart/Flutter: How to create loop of 600 days, with DateTime variable and return in text widget?
Dart/Flutter: How to create loop of 600 days, with DateTime variable and return in text widget?

Time:11-20

User writes a date for example 19/11/2021 and flutter print in Text Widget a List of days that finish after 600 days (19/11/2021 600).

CodePudding user response:

Here is the whole code which will print all day for next 600 days.

class MyApp extends StatelessWidget {
  final DateTime userDate = DateTime.now();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ListView.builder(
            itemCount: 600,
            itemBuilder: (_, index) {
                return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('${userDate.add(Duration(days: index)).day}'),
                );
            },
          )
        ),
      ),
    );
  }
}

For GridView:

Center(
      child: GridView.count(
        crossAxisCount: 2,
        children: List.generate(600, (index) {
              return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('${userDate.add(Duration(days: index)).day}'),
              );
          }
        )
      )
    ),

You can directly check on https://dartpad.dartlang.org/

CodePudding user response:

Maybe you can try something like this ?

class Test extends StatelessWidget {
  final DateTime userDate = DateTime.now();
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 600,
      itemBuilder: (_, index) {
        return Text(userDate.add(Duration(days: index)).toString());
      },
    );
  }
}

Prints all dates starting the date provided and ending after 600 days.

CodePudding user response:

Basically, it is a loop that is incremented by day:1 until for 600 times.

 List<Widget> generatedDateText(DateTime dateTime) {
      List<Text> _widgets = [];

      List.generate(600, (index) {
        final DateFormat formatter = DateFormat('yyyy-MM-dd');

        _widgets.add(
          Text(formatter.format(dateTime)),
        );

        dateTime = dateTime.add(
          const Duration(days: 1),
        );
      });

      setState(() {});

      return _widgets;
    }

And tested like

 SingleChildScrollView(
          child: Center(
              child: Column(children: [
            ...generatedDateText(_initDate),
          ])),
        ),

on state class DateTime _initDate = DateTime(2021, 11, 19);

You can reassign the date on _initDate.

  • Related