简体   繁体   中英

Can you use a class name in a conditional statement?

I have a custom widget that uses a ListTile. I would like to set the Leading: property to a Checkbox if the Class A is building the widget, but set the Leading property to Null if Class B is building the widget.

Is it possible for the ListTile to know the name of the class that is building it?

Or is there a better way to approach this type of problem?

You can either use the is operator or use obj.runtimeType to check the type of object.

Refer to this link to understand the difference between them.

Here's an example snippet.

    class CustomListTile{
         var obj;
         CustomListTile(this.obj);
         void isSameClass(){
            //  if(obj.runtimeType == Truck)
            if(obj is Truck){
              print("Building checkbox");
            }else{
              print("returning Null");
            }
         }
     }
        
    class Chopper{
      
      void test(){
        CustomListTile obj = CustomListTile(this);
        obj.isSameClass();
      }
    }
    
    class Truck{
      
      void test(){
        CustomListTile obj = CustomListTile(this);
        obj.isSameClass();
      }
    }
    
    void main(){
        Chopper objChop = Chopper();
        objChop.test();
      
        Truck objTruck = Truck();
        objTruck.test();
    
    }

Would passing a boolean like this do the job for you?


class CustomListTile extends StatelessWidget {
  const CustomListTile({Key? key, this.hasLeading = false}) : super(key: key);

  final bool hasLeading;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: hasLeading ? const Icon(Icons.person) : null,
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        CustomListTile(hasLeading: true), // This one has leading
        CustomListTile(), // This one does not
      ],
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM