I have a dynamic list as given below
List<dynamic> question = [" Elephants", "are", "the", 1, "land", 2, "on", 3];
I’m using a listview.builder to use this list on the screen to populate ui. What I want is to identify the int and show container with a red color and if it is string i want a container with blue color. How can i identiy the type of elements in the list
ListView.separated(
itemBuilder: (context, index) {
if (question.indexOf(int)) { // how to identify the type
return Container(color:Colors.red);
} else {
return Container(color:Colors.blue);
}
},
separatorBuilder: (context, index) => const SizedBox(
width: 6,
),
itemCount: question.length),
3
Answers
Use
is
for type checks.In Dart, you can check the type of an object using the
is
keyword or theruntimeType
property.Using the
is
keyword: The is keyword is used to check if an object is of a certain type. It returns a boolean value indicating whether the object is of the specified type or not.Using the
runtimeType
property: The runtimeType property returns the actual runtime type of an object.You can use
is
operator to checkType
of any objectExample:
To use it in
UI
file you can check following example: