How do i use Gradient with Flutter ThemeData backgroundColor property?

Viewed 1145

is it possible to set Gradient Colors instead of a single color in flutter ThemeData's backgroundColor property?

final ThemeData base = ThemeData.light();
return base.copyWith(
  visualDensity: VisualDensity.adaptivePlatformDensity,
  textTheme: _texttheme(base.textTheme),
  buttonTheme: _buttonTheme(base.buttonTheme),
  inputDecorationTheme: _inputDecorationTheme(base.inputDecorationTheme),
  bottomAppBarTheme: _bottomAppBarTheme(base.bottomAppBarTheme),

  backgroundColor: Colors.blueGrey // gradient color instead of single color
);

enter image description here

1 Answers

You can't directly use a gradient in backgroundColor since it accepts a Color and not a Gradient, but that doesn't mean you can't make your own custom background.

If you need to update the color throughout the entire application, you may try making your own custom Scaffold. Otherwise, the following GradientBackground will let you easily create a widget with a gradient background, but you may need to customize it depending on your layout needs (such as adding alignment properties to the Stack.

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: GradientBackground(
          gradient: LinearGradient(
            colors: [Colors.lightBlue, Colors.purpleAccent],
          ),
          child: Center(child: Text("Hello World!",
            style: Theme.of(context).textTheme.headline3,
          )),
        ),
      )
    );
  }
}

class GradientBackground extends StatelessWidget {
  GradientBackground({Key key, this.gradient, this.child}) : super(key: key);
  final Gradient gradient;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: gradient,
          ),
        ),
        child,
      ],
    );
  }

}

GradientBackground results

Related