【问题标题】:Define gradient of AppBar in AppBarTheme within ThemeData在 ThemeData 中的 AppBarTheme 中定义 AppBar 的渐变
【发布时间】:2021-06-22 10:45:08
【问题描述】:

我正在尝试在flutter 中创建应用程序主题数据,并且在定义ThemeData 时,我想使用渐变外观自定义我的应用程序的AppBar。现在,在ThemeData 中,我们有AppBarTheme 选项,但不确定如何使用AppBarTheme 定义渐变。

但是,在Scaffold 中使用AppBar 我能够定义渐变,但正在寻找一种在ThemeData 中定义它的方法

以下是渐变的工作代码,但在 Scaffold 中,不知道如何在 AppBarTheme 中添加 flexibleSpace

return Scaffold(
      appBar: AppBar(
       
        title: Text(
          'Dashboard',
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: <Color>[
                const Color(0xFFD26934),
                const Color(0xFFFF9B44),
              ],
            ),
          ),
        ),
      ),

想在这里定义渐变

ThemeData(
    fontFamily: 'Lato-Regular',
    appBarTheme: AppBarTheme(
      titleTextStyle: TextStyle(color: Colors.white),
    ),
  ),

【问题讨论】:

    标签: flutter dart flutter-layout flutter-appbar


    【解决方案1】:

    package:flutter/material 尝试实现 Google 的 Material Design:https://material.io/design

    这是一组特定的样式指南,由 Google 开发,并制定了某些规则。他们制定的规则之一是应用栏应该是纯色(即不是渐变)。

    因为 Flutter 试图匹配这个规范,所以它不允许在 AppBar 小部件中使用渐变。但你总是可以自己制作。

    例如:

    class GradientAppBar extends StatelessWidget with PreferredSizeWidget {
      @override
      Widget build(BuildContext context) => DecoratedBox(
        child: Text('My Title'),
        decoration: BoxDecoration(
          gradient: // your gradient here
        ),
      );
    
      @override
      Size get preferredSize => Size(double.infinity, 60);  
    }
    

    注意,如果您想将自定义应用栏传递给Scaffold.appBar,它需要实现PreferredSizeWidget 并覆盖preferredSize,这样脚手架就知道要让它有多大。

    您可能还想将titleactions 等内容提取到GradientAppBar 的参数中,以便您可以重复使用它

    【讨论】:

      【解决方案2】:

      你问的是不可能的。可悲的是,您无法为颜色分配渐变。唯一的方法是使用灵活空间。

      appBar: AppBar(
                centerTitle: true,
                  title: Text(widget.title),
                  flexibleSpace: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: <Color>[
                        Colors.red,
                        Colors.blue
                      ])          
                   ),        
               ),      
           ),
      

      【讨论】:

        猜你喜欢
        • 2018-10-28
        • 2019-12-06
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 2021-02-02
        • 2021-08-20
        相关资源
        最近更新 更多