i have alot of similar containers in my app that hold varied pieces of text. I want to make a Dart Function that i can then use to return the container and the specify color and text height and width.
when I try to make the Dart Function:
Container MyContainer() {}
the MyContainer part is coming back with the error: The body might complete normally, causing 'null' to be returned, but the return type, 'Container', is a potentially non-nullable type
I've looked at the docs but don't understand how the common fixes would be implemented into the function.
cheers
CodePudding user response:
Just create a class extending StatelessWidget
like this :
class MyCustomContainer extends StatelessWidget {
const MyCustomContainer({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
// Do what you want
);
}
}
Or you can also do it quickly as a getter Widget
inside another class
Widget myCustomContainer() {
return Container(
// Do what you want
);
}
And just call it inside your tree in build()
CodePudding user response:
You have two options:
1.Use functions that return Container
. For Example,
Container MyContainer({required Color color, required String label, double width = 200, double height = 300}) { return Container( height: height, width: width, decoration: BoxDecoration( color: color, ), child: Text(label), ); }
But that's not a correct way to create a Reusable Widget
.
The optimal way is:
- Extract a
custom StatelessWidget class
for that widget. Like this.
class MyContainer extends StatelessWidget { const MyContainer({Key? key, this.width = 200, this.height = 300, required this.label, required this.color}) : super(key: key); final double width; final double height; final String label; final Color color; @override Widget build(BuildContext context) { return Container( width: width, height: height, decoration: BoxDecoration( color: color, ), child: Text(label), ); } }