Search code examples
flutterflutter-layout

how to make a Dart Function that holds a container?


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


Solution

  • 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:

    1. 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),
        );
      }
    }