skip to Main Content

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


  1. Use is for type checks.

    if(question[i] is int){
    
    } else if(question[i] is String){
    
    } else {
    
    }
    
    Login or Signup to reply.
  2. In Dart, you can check the type of an object using the is keyword or the runtimeType property.

    1. 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.

      if(question[i] is int) {
      
      } else if(question[i] is String) {
      
      }
      
    2. Using the runtimeType property: The runtimeType property returns the actual runtime type of an object.

      if(question[i].runtimeType==String) {
      
      } else if(question[i].runtimeType==int) {
      
      }
      
    Login or Signup to reply.
  3. You can use is operator to check Type of any object

    Example:

    List<dynamic> question = [" Elephants", "are", "the", 1, "land", 2, "on", 3];
    
    for(var element in question) {
       if(element is String) {
          // current element is String. Handle accordingly
       } else if (element is int) {
          // current element is int. Handle accordingly
       } else {
          // unknown or any other type. Handle accordingly
       }
    }
    

    To use it in UI file you can check following example:

    ListView.separated(itemBuilder: (context, index) => question[index] is String ? Container(
       decoration: BoxDecoration(
        color: Colors.green,
       ),
       child: Center(
         child: Text("String"),
        ),
      ) : question[index] is int ? Container(
        decoration: BoxDecoration(
        color: Colors.yellow,
        ),
        child: Center(
         child: Text("int"),
        ),
      ) : Container(
        decoration: BoxDecoration(
        color: Colors.red,
        ),
        child: Center(
         child: Text("Unknown"),
        ),
      ), 
        itemCount: question.length);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search