Reputation: 417
I've created a list of dates. I want to render it in a list of widgets but I'm getting an error: type 'List' is not a subtype of type 'List'. Is there a better way to render a list of dates?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Basic List';
var start = DateTime.now();
var end = DateTime(2021, 12, 31);
var list = [];
while (start.isBefore(end)) {
list.add(start);
start = start.add(Duration(days: 1));
}
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: getDaysInWeek(),
),
),
),
);
}
}
List<Widget> getDaysInWeek() {
var start = DateTime.now();
var end = DateTime(2021, 12, 31);
var list = [];
while (start.isBefore(end)) {
list.add(start);
start = start.add(Duration(days: 1));
}
return list.toList();
}
Upvotes: 1
Views: 664
Reputation: 126684
You need to map your List<DateTime
to List<Widget
. Intuitively this is necessary because you cannot display DateTime
in Flutter, you can only display Widget
s!
This could look like this:
List<Widget> get daysInWeek {
final end = DateTime(2021, 12, 31), list = <DateTime>[];
DateTime start = DateTime.now();
while (start.isBefore(end)) {
list.add(start);
start = start.add(const Duration(days: 1));
}
return list.map((DateTime time) {
return Text(time.toString());
}).toList();
}
You will notice two things:
I mapped the DateTime
objects to Text
objects and Text
is a widget that displays String
s as text.
The syntax is a little different in a few places to be more idiomatic Dart code. I am sure you will intuitively understand this syntax.
Upvotes: 1