【问题标题】:flutter - use theme in applicationflutter - 在应用程序中使用主题
【发布时间】:2021-10-11 23:41:34
【问题描述】:

我有以下代码在我的应用程序的一部分中有一个特定的主题:

  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        textTheme: Theme.of(context).textTheme.copyWith(
          bodyText2: TextStyle(color: Colors.green),
        )
      ),
      child: Center(
        child: Text('Hello', ),

我想使用我为文本“Hello”定义的 bodyText2 来获得绿色。实际上,我希望文本具有样式名称“bodyText2”和相应的样式(在这种情况下为绿色)。 你能帮帮我吗?

【问题讨论】:

    标签: flutter widget themes


    【解决方案1】:

    您可以为您的应用尝试 2 个选项:

    1. 在您的MaterialApp 中定义a global theme
    MaterialApp(
      title: 'Sample App',
      theme: ThemeData(
        // Define the default TextTheme. Use this to specify the default
        // text styling for headlines, titles, bodies of text, and more.
        textTheme: const TextTheme(
          bodyText2: TextStyle(fontSize: 22, color: Colors.green), // Define your default Text style
          subtitle1: TextStyle(fontSize: 24, color: Colors.green), // Define your own subtitle style
        ),
      ),
      home: Scaffold(
          appBar: AppBar(title: Text('Sample title', style: Theme.of(context).textTheme.subtitle1)), // Use your config like this
          body: Text('Sample content'), // Without specifying style, the app will auto use your bodyText2 config
      ),
    );
    
    1. 在本地小部件级别定义 DefaultTextTheme
    Scaffold(
          body: DefaultTextStyle(
            style: TextStyle(color: Colors.green),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text(
                    'The first text', // A green color text
                  ),
                ],
              ),
            ),
          ),
        )
    

    DefaultTextThemecan be found here 上的一个很好的例子。

    您可以快速浏览official documentation,了解如何快速配置Text

    【讨论】:

      猜你喜欢
      • 2011-02-14
      • 2019-04-30
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多