'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,
);
}
}
Solution 1:[1]
class ReusableCard extends StatelessWidget {
final Color color;
ReusableCard():
this.color = const Color(0xFF1D1E20)
{
print('empty const is called');
}
....
}
Solution 2:[2]
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,
);
}
}
Solution 3:[3]
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,
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dali Hamza |
| Solution 2 | quoci |
| Solution 3 |
