I'm trying to form a Container with Text objects in Flutter. The data for those Text objects are coming from a List. I'm relatively new to Dart and Flutter, so i can't figure out why i can only pass strings in a map() method and not maps.
child: Column(
children: tasks.map((value) => ColumnChild(value['title'])).toList()
)
The code above basically works. However, i want to just pass only the value in, but that errors.
This is where i create the object:
class ColumnChild extends StatelessWidget {
String title;
ColumnChild(this.title);
@override
Widget build(BuildContext context) {
print(title);
return Container(
width: double.infinity,
height: 50 ,
child: Column(
children: [
Text(title)
],
)
);
}
}
Thanks in advance!
CodePudding user response:
ColumnChild
asks for a string called title
. If you give it a map, flutter gets confused.
Imagine maps are dictionaries and strings are words. Your widget ColumnChild
asked for a word and you gave it the whole dictionary, without teaching it how to look up a word.
Let's teach it how to look up a word:
class ColumnChild extends StatelessWidget {
// you can put any name instead of data but don't forget to replace it in your code
final Map<String, dynamic> data;
const ColumnChild(this.data, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
height: 50,
child: Column(
children: [Text(data['title'] ?? 'not found')],
));
}
}
Now instead of coming to you asking for a word, it asks for the dictionary and looks up the words by itself and you can do this:
child: Column(
children: tasks.map((value) => ColumnChild(value)).toList()
)
CodePudding user response:
Instead of using the .map(), You could loop through the list and use the Strings directly
Column(
children: [
for(var a in tasks)
Text(a)
),
Or You use a listView.builder
ListView.builder(
itembuilder: (context,index){
return Text(tasks[index])
},
itemCount: tasks.length
)