如何在一行 widget 中创建两个文本小部件

5

我是Flutter的初学者,想要在一行中显示两个文本。其中“hello”是第一个文本小部件,“world”是另一个文本小部件。

尝试使用我的基础知识来做到这一点,但遇到了以下错误:

水平RenderFlex有多个子项,其textDirection为空,因此布局顺序未定义。 'package:flutter/src/rendering/flex.dart': 失败断言:line 439 pos 18: 'textDirection!= null'

    class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Row(
      children: <Widget>[
        Text("hello",textDirection: TextDirection.rtl,),
        Text("world",textDirection: TextDirection.rtl,)
      ],
    );
  }
}
5个回答

14

也许您想使用 RichText 代替?

RichText(
  text: TextSpan(
    children: <TextSpan>[
      TextSpan(text: 'hello', style: TextStyle(color: Colors.red)),
      TextSpan(text: ' world', style: TextStyle(color: Colors.blue)),
    ],
  ),
)

1
请阅读关于Flutter中行(Row)的链接:

https://medium.com/jlouage/flutter-row-column-cheat-sheet-78c38d242041

简而言之,您需要声明一行,该行中的项目是子项(必须是小部件)。
我从这里选择了一个示例 https://flutter.dev/docs/development/ui/layout 类似于这样
Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    Image.asset('images/pic1.jpg'),
    Image.asset('images/pic2.jpg'),
    Image.asset('images/pic3.jpg'),
  ],
);

在您的情况下,您只需删除image.asset并将其更改为文本即可...
Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    Text('Hello'),
    Text('World'),

  ],
);

或者你想要什么。

0
请尝试以下代码:-
@override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text("Hello",style: TextStyle(color: Colors.blue)),
        Text("World",style: TextStyle(color: Colors.blue))
      ],
    );
}

0
**Try This Simplest Way**

import 'package:flutter/material.dart';
class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Row(
          children: <Widget>[
        Text("Hello"),
        Text("World"),
          ],
        ),
      ),
    );
  }
}

0
我把“行”改成了“列”,然后它就正常工作了。
child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: const [
              Text(
                'Good Morning!',
                style: TextStyle(color: Colors.green, fontSize: 30),
              ),
              Text('scott'),
              GradientContainer(),
              textMy(),
            ],
          ),

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