如何在Flutter中设置文本背景?

42

我对Flutter非常陌生,但我很有兴趣从基础开始学习。

现在我正在尝试诸如更改一些文本的背景颜色这样的基本事情,但我卡住了。

import 'package:flutter/material.dart';

void main() {

  final barColor = const Color(0xFFD63031);

  var app = MaterialApp(    
    home: Scaffold(    
      backgroundColor: barColor,    
    ),    
  );

  Center(    
    child: Text('My Text',      
      textDirection: TextDirection.ltr,    
    ),    
  );
      runApp(app);
}

我知道为什么文本没有显示,但是我已经努力解决了好几天了,尝试了许多不同的方法都没有成功,所以非常感谢任何帮助。

谢谢

2个回答

84

简而言之 - (更新于07-08-2019)

使用样式属性(backgroundColor)

Text(
  'Some text...',
  style: TextStyle(backgroundColor: Colors.blue),
)

使用样式属性(background

Text(
  'Some text...',
  style: TextStyle(background: Paint()..color = Colors.blue),
)

使用DecoratedBox

const DecoratedBox(
  decoration: const BoxDecoration(color: Colors.blue),
  child: const Text('Some text...'),
);

长答案

首先,欢迎来到Flutter和StackOverflow :)

这是因为你误解了在Flutter中开发的方法。与其他架构不同,你不是从main()函数开始实例化变量/对象并从那里开发流程,而是同样从main()函数开始构建你的小部件树,通常使用MaterialAppCupertinoApp并适配其所有子元素以创建你的应用程序。

因此,为了得到你想要的东西,举个例子,你必须将Center小部件作为你的Scaffold主体添加,并为你的Text小部件提供TextStyle,提供color属性。我给它设为蓝色,但你可以给它任何你想要的颜色。因此,这是你重构后的代码:

void main() => runApp(
      MaterialApp(
        home: Scaffold(
          backgroundColor: const Color(0xFFD63031),
          body: Center(
            child: Text(
              'MyText',
              textDirection: TextDirection.ltr,
              style: TextStyle(
                background: Paint()..color = Colors.blue,
              ),
            ),
          ),
        ),
      ),
    );

这将提供以下结果

示例

我建议您查看Awesome Flutter代码库,其中包含大量很好的Flutter内容,可以帮助您入门。


太棒了!非常感谢你的完整回答。非常感激 :) - J.W
TextStyle has a backgroundColor property - you can simply set it, instead of creating new Paint() - Alex Semeniuk
@AlexSemeniuk 谢谢,这可能已经在此期间添加了。我会相应地更新我的答案。 - Miguel Ruivo

1
简单的方法是在 style 属性中设置它。
Text(
  'My Text...',
  style: TextStyle(backgroundColor: Colors.grey),
)

你可以在 style: TextStyle() 中设置多个 text 属性。
{ bool inherit = true, 
  Color color, 
  Color backgroundColor, 
  double fontSize, 
  FontWeight fontWeight, 
  FontStyle fontStyle, 
  double letterSpacing, 
  double wordSpacing, 
  TextBaseline textBaseline, 
  double height, 
  Locale locale, 
  Paint foreground, 
  Paint background, 
  List<Shadow> shadows, 
  List<FontFeature> fontFeatures, 
  TextDecoration decoration, 
  Color decorationColor, 
  TextDecorationStyle decorationStyle, 
  double decorationThickness, 
  String debugLabel, 
  String fontFamily, 
  List<String> fontFamilyFallback, 
  String package
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接