如何将渐变与 Flutter ThemeData backgroundColor 属性一起使用?

Gok*_*dar 3 dart flutter

是否可以在flutter ThemeData的backgroundColor属性中设置渐变颜色而不是单一颜色?

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
);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Lin*_*ous 7

您不能直接使用渐变,backgroundColor因为它接受 aColor而不是 a Gradient,但这并不意味着您不能制作自己的自定义背景。

如果您需要更新整个应用程序的颜色,您可以尝试制作自己的自定义Scaffold. 否则,以下内容GradientBackground将让您轻松创建具有渐变背景的小部件,但您可能需要根据布局需求对其进行自定义(例如向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,
      ],
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

渐变背景结果