I would like to make a List in Flutter. List consists of more than one type of widget. I made it this way:
child: ListView.builder(
itemCount: datasource.length,
itemBuilder:(context, index) {
if (datasource[index] == "red") {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.white,
),
height: 80,
margin: EdgeInsets.all(10),
);
}
else {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.white,
),
height: 80,
margin: EdgeInsets.all(10),
);
}
},
),
But now I need to add more types of widgets and the code starts to be unclear. Is there any way to move "if else" part to another file?
I have already tried make a method, but failed to import it to original file with List.builder.
2
Answers
You can create a separate file, let’s say widget_helper.dart, and define a function to handle the creation of the containers based on the color.
In widget_helper.dart
And in your original file:
import ‘widget_helper.dart’;
Make different class for different type of widget
widget_list.dart
Use the Widgets class in ListView.builder:
It is more readable and manageable.