如何使用Flutter设置文本背景?

J.W*_*J.W 5 flutter flutter-layout

我是新手,但从一开始我就对学习它很感兴趣。

现在,我正在尝试一些基本的操作,例如更改某些文本的背景颜色,但是我遇到了麻烦。

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);
}
Run Code Online (Sandbox Code Playgroud)

我确实理解为什么文本没有显示,但是我已经为此工作了好几天,并且我尝试了许多不同的尝试而没有成功,所以我们将不胜感激。

谢谢

Mig*_*ivo 19

TL; DR-(已更新07-08-2019)

使用样式属性(backgroundColor

Text(
  'Some text...',
  style: TextStyle(backgroundColor: Colors.blue),
)
Run Code Online (Sandbox Code Playgroud)

使用样式属性(background

Text(
  'Some text...',
  style: TextStyle(background: Paint()..Colors.blue),
)
Run Code Online (Sandbox Code Playgroud)

用一个 DecoratedBox

const DecoratedBox(
  decoration: const BoxDecoration(color: Colors.blue),
  child: const Text('Some text...'),
);
Run Code Online (Sandbox Code Playgroud)

长答案

首先,欢迎使用Flutter和StackOverflow :)

发生这种情况是因为误解了您应该使用Flutter开发的方式。与其他从main()函数开始的架构发生的情况相反,使您的vars / objects变得不稳定,并从那里开始开发流程,使用Flutter,您也从main()函数开始创建小部件树,通常使用a MaterialAppCupertinoAppand适合其所有子元素创建您的应用。

因此,作为例子来得到你想要的东西,你必须添加Centerwidget作为你的身体Scaffold ,然后给一个TextStyle你的Text小部件,提供的财产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,
              ),
            ),
          ),
        ),
      ),
    );
Run Code Online (Sandbox Code Playgroud)

将提供以下结果

例

我建议您看看Awesome Flutter仓库,那里有很多很好的Flutter内容,可以真正帮助您。