【问题标题】:How do i use Gradient with Flutter ThemeData backgroundColor property?如何将渐变与 Flutter ThemeData backgroundColor 属性一起使用?
【发布时间】:2020-10-24 16:02:29
【问题描述】:

是否可以在 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
);

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您不能直接在backgroundColor 中使用渐变,因为它接受Color 而不是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,
          ],
        );
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 1970-01-01
      • 2021-11-16
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      相关资源
      最近更新 更多