Подтвердить что ты не робот

Текст с переворачиванием флаттера

Я хочу обернуть текст по мере роста текста. Я просмотрел и попробовал обернуть почти все, но текст остается одной строкой и переполняется с экрана. Кто-нибудь знает, как добиться этого? Любая помощь высоко ценится!

Positioned(
    left: position.dx,
    top: position.dy,
    child: new Draggable(
      data: widget.index,
      onDragStarted: widget.setDragging,
      onDraggableCanceled: (velocity, offset) {
        setState(() {
          position = offset;
          widget.secondCallback(offset, widget.index);
          widget.endDragging();
        });
      },
      child: new GestureDetector(
        onTap: () {
          widget.callback(widget.caption, widget.index);
        },
        child: new Text(
            widget.caption.caption,
            style: new TextStyle(
              color: widget.caption.color,
              fontSize: widget.caption.fontSize,
            ),
          ),
      ),
      feedback: new Material(
        type: MaterialType.transparency,
        child: new Text(
          widget.caption.caption,
          style: new TextStyle(
              color: widget.caption.color,
              fontSize: widget.caption.fontSize),
          softWrap: true,
        ),
      ),
    ));
4b9b3361

Ответ 1

В моем проекте я переношу Text экземпляры вокруг Container. Этот конкретный пример кода содержит два уложенных объекта Text.

Вот пример кода.

    //80% of screen width
    double c_width = MediaQuery.of(context).size.width*0.8;

    return new Container (
      padding: const EdgeInsets.all(16.0),
      width: c_width,
      child: new Column (
        children: <Widget>[
          new Text ("Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 ", textAlign: TextAlign.left),
          new Text ("Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2", textAlign: TextAlign.left),
        ],
      ),
    );

[edit] Добавлено ограничение ширины контейнера

Ответ 2

Использовать расширенный

 Expanded(
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                new Text(_name, style: Theme.of(context).textTheme.subhead),
                new Container(
                  margin: const EdgeInsets.only(top: 5.0),
                  child: new Text(text),
                ),
              ],
            ),

Ответ 3

Это сработало для меня

new Container(
       child: Row(
         children: <Widget>[
            Flexible(
               child: new Text("A looooooooooooooooooong text"))
                ],
        ));

Без ширины Контейнера, Гибкая обертка текста.

Ответ 4

Если это один текстовый виджет, который вы хотите обернуть, вы можете использовать Гибкие или Расширенные виджеты.

Expanded(
  child: Text('Some lengthy text for testing'),
)

или

Flexible(
  child: Text('Some lengthy text for testing'),
)

Для нескольких виджетов вы можете выбрать Wrap виджет. Для более подробной информации проверьте это

Ответ 5

Container(
                          color: Color.fromRGBO(224, 251, 253, 1.0),
                          child:ListTile(
                            dense: true,
                            title: Column(
                              crossAxisAlignment:CrossAxisAlignment.start,
                              children: <Widget>[
                                RichText(
                                  textAlign: TextAlign.left,
                                  softWrap: true,
                                  text: TextSpan(children: <TextSpan>
                                  [
                                    TextSpan(text:"hello: ",style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold)),
                                    TextSpan(text:"I hope this helps",style: TextStyle(color: Colors.black)),
                                  ]
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

Ответ 6

Вы можете использовать Flexible, в этом случае person.name может быть длинным именем (Labels и BlankSpace являются пользовательскими классами, которые возвращают виджеты):

new Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: <Widget>[
   new Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        new Flexible(
            child: Labels.getTitle_2(person.name,
            color: StyleColors.COLOR_BLACK)),
        BlankSpace.column(3),
        Labels.getTitle_1(person.likes())
      ]),
    BlankSpace.row(3),
    Labels.getTitle_2(person.shortDescription),
  ],
)

Ответ 7

Вы можете обернуть свой виджет с помощью гибкого виджета, а затем установить свойство текста, используя свойство переполнения виджета текста. Вы должны установить TextOverflow.клип например: -

Flexible
(child: new Text("This is Dummy Long Text",
 style: TextStyle(
 fontFamily: "Roboto",
 color: Colors.black,
 fontSize: 10.0,
 fontWeight: FontWeight.bold),
 overflow: TextOverflow.clip,),)

надеюсь, это поможет кому-то :)

Ответ 8

Использование многоточия

Text(
  "This is a long text",
  overflow: TextOverflow.ellipsis,
),

enter image description here


Использование Fade

Text(
  "This is a long text",
  overflow: TextOverflow.fade,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Использование клипа

Text(
  "This is a long text",
  overflow: TextOverflow.clip,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Примечание:

Если вы используете Text внутри Row, вы можете поставить над Text внутри Expanded, например:

Expanded(
  child: AboveText(),
)

Ответ 9

Попробуйте Wrap-widget для переноса текста по мере роста текста:

Пример:

Wrap(  
 direction: Axis.vertical, //Vertical || Horizontal
 children: <Widget>[
            Text(Your Text,style: TextStyle(fontSize: 30),),
            Text(Your Text,style: TextStyle(fontSize: 30),),
            ],//<widget>  )//wrap

Ответ 10

Вы можете использовать плагин FLUTTER_ MARKDOWN, чтобы сделать эту работу более простым способом... Перейдите к PUB.DEV и

получить ссылку Flutter_markdown пакета link

Чтобы понять код ниже, пожалуйста,

добавьте эту зависимость flutter_markdown: ^ 0.2.0 в свой файл pubspec.yaml

Затем вставьте следующий код в файл main.dart file .

import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';

const String _addYourLongText = """# Markdown Example
Markdown allows you to easily include formatted text, images, and even formatted Dart code in your app.
## Styling
Style text as _italic_, __bold__, or 'inline code'.
- Use bulleted lists
- To better clarify
- Your points
## Links
You can use [hyperlinks](hyperlink) in markdown
## Images
You can include images:
![Flutter logo](https://flutter.io/images/flutter-mark-square-100.png#100x100)
## Markdown widget
This is an example of how to create your own Markdown widget:
    new Markdown(data: 'Hello _world_!');
## Code blocks
Formatted Dart code looks really pretty too:


Enjoy!
""";

void main() {
  runApp(new MaterialApp(
    title: "Markdown Demo",
    home: new Scaffold(
      appBar: new AppBar(title: const Text('Markdown Demo')),
      body: const Markdown(data: _addYourLongText)
    )
  ));
}

Затем запустите свое приложение, и вы получите удивительную длинную страницу трепетания текста....

Вы можете получить код GitHub здесь

Ответ 11

Вы можете использовать Контейнер и задать ширину, Текст, когда дочерний элемент будет автоматически обернут

Container(
  width: 230.0,
  child: Text(
    "long text"
  ),
);