Flutter - Create a custom styled Container widget which "projects" child content

354 views Asked by At

I want to create a custom container widget that always has a gradient background. The reason is to only code the gradient in one place, so it can be changed in one place and yet affect the whole app.

I have this in my view:

child: Container(
      height: double.infinity,
      width: double.infinity,
      padding: const EdgeInsets.all(40),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: const Alignment(1, -1.0),
          end: const Alignment(-0.3, 0.0),
          colors: [
            initialGradientColor,
            Theme.of(context).colorScheme.primary
          ],
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [...more code...

Can I extract to a Container widget like so?:

class GradientContainerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: // ****************** project content into here... ****************
      height: double.infinity,
      width: double.infinity,
      padding: const EdgeInsets.all(40),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: const Alignment(1, -1.0),
          end: const Alignment(-0.3, 0.0),
          colors: [initialGradientColor, Theme.of(context).colorScheme.primary],
        ),
      ),
    );
  }
}

I would need to find a way to add a child into GradientContainerWidget. Is there a way to project content into the child of the widget?.

The usage in the view would be something like this:

child: GradientContainerWidget(
                child: Column(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [..... more children....])
            );
1

There are 1 answers

0
Anas On BEST ANSWER

If you looking on how to add a child then you can create a constructor and pass it as Widget.

class GradientContainerWidget extends StatelessWidget {

  final Widget child;

  GradientContainerWidget({this.child}); //you can pass key to

  @override
  Widget build(BuildContext context) {
    return Container(
      child: child
      height: double.infinity,
      width: double.infinity,
      padding: const EdgeInsets.all(40),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: const Alignment(1, -1.0),
          end: const Alignment(-0.3, 0.0),
          colors: [initialGradientColor, Theme.of(context).colorScheme.primary],
        ),
      ),
    );
  }
}