【问题标题】:can I set style of my container in theme data?我可以在主题数据中设置容器的样式吗?
【发布时间】:2021-08-05 02:29:01
【问题描述】:

要在我的容器中制作圆角,我可以这样做

Container(
  decoration: BoxDecoration(
    borderRadius: BorderRadius.all(Radius.circular(20))
  ),
  child: ...
)

但是每当我创建一个圆角的容器时,我都需要一遍又一遍地做。我可以在我的主题数据中设置它吗?我可以像下面的代码一样在主题数据中设置我的 appBar 主题,但我需要类似的东西,但对于容器。该怎么做?

final themeData = ThemeData(
  appBarTheme: _appBarTheme,
);

const AppBarTheme _appBarTheme = const AppBarTheme(
  elevation: 2,
  centerTitle: true,
  color: const Color.fromRGBO(245, 245, 245, 1),
  textTheme: TextTheme(
    // center text style
    headline6: TextStyle(color: Colors.black, fontSize: 16),
    // Side text style
    bodyText2: TextStyle(color: Colors.black),
  ),
);

【问题讨论】:

    标签: flutter dart containers flutter-widget


    【解决方案1】:

    我认为你最好的选择可能是隔离一个容器并使用下面的示例等参数自定义这个新小部件。

    class CustomContainerWdt extends StatelessWidget {
      final Color? color;
      final Widget child;
      final String text;
    
      const CustomContainerWdt({Key key, this.color, this.child, this.text}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          decoration: BoxDecoration(
            color: color ?? Theme.of(context).primaryColor,
            borderRadius: BorderRadius.all(Radius.circular(20))
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('$text'),
              child,
            ],
          ),
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以提供一个主题来包装您的容器以提供一个主题

         Theme(
            // Create a unique theme with "ThemeData"
            data: ThemeData(
              textTheme: /* Your Text Theme*/,
            ),
            child: Container(
              onPressed: () {},
              child: Text("Your Text Here"),
            ),
          );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 1970-01-01
        • 2021-11-17
        • 2022-06-27
        • 1970-01-01
        相关资源
        最近更新 更多