flutter - 如何用 Flutter 设置文字背景?

标签 flutter flutter-layout

我对 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);
}

我确实理解为什么文本没有显示,但我已经为此工作了几天,并且我尝试了很多不同的事情但没有成功,因此非常感谢任何帮助。

谢谢

最佳答案

TL;DR -(2019 年 7 月 8 日更新)

使用样式属性(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() 函数开始的其他架构不同,实例化你的 vars/objects 并从那里开发你的流程,使用 Flutter 你从 main 开始你的小部件树() 函数,通常使用 MaterialAppCupertinoApp 并适合其所有子级来创建您的应用程序。

因此,作为获得所需内容的示例,您必须将 Center 小部件添加为 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,
              ),
            ),
          ),
        ),
      ),
    );

这将提供以下结果

example

我建议你看看Awesome Flutter repo,你有很多很好的 Flutter 内容可以开始,这真的可以帮助你。

关于flutter - 如何用 Flutter 设置文字背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807975/

相关文章:

android - Firebase 登录方法是signInWithEmailAndPassword(email, password);在 flutter 中使用发送散列密码?

forms - 如何从另一个屏幕重置 Flutter 中的表单?

flutter - Orientation Builder 给出了错误的方向

Flutter TextFormField TextInputAction.done 不是带有键盘类型数字的选项

flutter - 带有 float 操作按钮的底部导航栏 flutter

flutter - 生成加权随机字母列表

Flutter,如何在侧面添加选项卡按钮?

flutter - 如何使用从共享首选项json文件中获取的数据的返回值作为参数

flutter - Flutter中的Material和MaterialApp有什么区别?

dart - 我可以在 <Text> 中呈现数字之前对其进行格式化吗