简体   繁体   中英

how to create empty constructor in dart?

Here I want to create an empty constructor to print empty constructor is called message but it shows try adding initializer error.

class ReusableCard extends StatelessWidget {
  final Color color;

  ReusableCard(){    
print('empty const is called');   
 }

  ReusableCard(this.color);

  @override   Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15.0),
      //TODO:use decorator only if colors are added inside in it.

      decoration: BoxDecoration(
        color: Color(0xFF1D1E20),
        borderRadius: BorderRadius.circular(10.0),
      ),
      // width: 100,
      height: 100,
    );   
}
}
class ReusableCard extends StatelessWidget {
  final Color color;

  ReusableCard():
     this.color = const Color(0xFF1D1E20)
     {    
       print('empty const is called');   
     }

  ....
}


Since your color variable is final you have to initialize it on your empty constructor.

class ReusableCard extends StatelessWidget {
  final Color color;

  ReusableCard() {
    this.color = const Colors.blue;
    print('empty const is called');
  }

  ReusableCard(this.color);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15.0),
      //TODO:use decorator only if colors are added inside in it.

      decoration: BoxDecoration(
        color: Color(0xFF1D1E20),
        borderRadius: BorderRadius.circular(10.0),
      ),
      // width: 100,
      height: 100,
    );
  }
}

Repeating the default constructor is not allowed in dart so you need to use named constructors as follows:

ReusableCard.empty() {
      print('empty');
   }

see your class:

class ReusableCard extends StatelessWidget {
     final Color color;

     ReusableCard.empty() {
          print('empty');
       }
     ReusableCard(this.color);

     @override   Widget build(BuildContext context) {
       return Container(
         margin: EdgeInsets.all(15.0),
        //TODO:use decorator only if colors are added inside in it.

         decoration: BoxDecoration(
          color: Color(0xFF1D1E20),
          borderRadius: BorderRadius.circular(10.0),
          ),
         // width: 100,
         height: 100,
         );   
         }
        }

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