Как сделать прокручиваемый текст флаттером?

У меня есть изображение в верхней части виджета Column, после этого есть заголовок, который является текстовым виджетом, а после этого есть еще один текстовый виджет, который содержит некоторое описание, выходит за пределы экрана и дает ошибку рендеринга.

Поэтому я хочу сделать это текстовое представление прокручиваемым, чтобы оно было полностью видимым и прокручиваемым. И его размер должен быть динамическим, как и данные, поступающие из API. Я пробовал несколько подходов, но не смог. Вот скриншот

Скриншот:

введите описание изображения здесь

@override


 Widget build(BuildContext context) {
    var size = MediaQuery
        .of(context)
        .size;
    final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
    final double itemWidth = size.width;


return new Container(
  child: new Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      new Padding(
        padding: const EdgeInsets.fromLTRB(0.0, 24.0, 0.0, 0.0),
        child: new Image.asset(
          'assets/img/noconnection.png',
          height: 200.0,
          width: itemWidth,
        ),
      ),
      new Padding(
        padding: const EdgeInsets.all(12.0),
        child: new Text(
          "Some Heading Text",
          style: new TextStyle(
              fontSize: 28.0,
              color: Colors.black87,
              fontWeight: FontWeight.w600),
        ),
      ),
      new SingleChildScrollView(
        child: new Text(
          "Description that is too long in text format(Here Data is coming from API)",
          style: new TextStyle(
            fontSize: 16.0, color: Colors.black87,
          ),
        ),
      ),
    ],
  ),
);

}


person Vaibhav Miniyar    schedule 03.04.2018    source источник


Ответы (5)


Вам нужно обернуть свой SingleChildScrollView в расширенный виджет, и вы получите то, что ищете.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var size = MediaQuery
        .of(context)
        .size;
    final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
    final double itemWidth = size.width;

    return new Container(
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          new Padding(
            padding: const EdgeInsets.fromLTRB(0.0, 24.0, 0.0, 0.0),
            child: new Image.asset(
              'assets/rp1.jpg',
              height: 200.0,
              width: itemWidth,
            ),
          ),
          new Padding(
            padding: const EdgeInsets.all(12.0),
            child: new Text(
              "Some Heading Text",
              style: new TextStyle(
                  fontSize: 28.0,
                  color: Colors.white,
                  fontWeight: FontWeight.w600),
            ),
          ),
          new Expanded(
            flex: 1,
            child: new SingleChildScrollView(
              scrollDirection: Axis.vertical,//.horizontal
              child: new Text(
                "1 Description that is too long in text format(Here Data is coming from API) jdlksaf j klkjjflkdsjfkddfdfsdfds " + 
                "2 Description that is too long in text format(Here Data is coming from API) d fsdfdsfsdfd dfdsfdsf sdfdsfsd d " + 
                "3 Description that is too long in text format(Here Data is coming from API)  adfsfdsfdfsdfdsf   dsf dfd fds fs" + 
                "4 Description that is too long in text format(Here Data is coming from API) dsaf dsafdfdfsd dfdsfsda fdas dsad" + 
                "5 Description that is too long in text format(Here Data is coming from API) dsfdsfd fdsfds fds fdsf dsfds fds " + 
                "6 Description that is too long in text format(Here Data is coming from API) asdfsdfdsf fsdf sdfsdfdsf sd dfdsf" + 
                "7 Description that is too long in text format(Here Data is coming from API) df dsfdsfdsfdsfds df dsfds fds fsd" + 
                "8 Description that is too long in text format(Here Data is coming from API)" + 
                "9 Description that is too long in text format(Here Data is coming from API)" + 
                "10 Description that is too long in text format(Here Data is coming from API)",     
                style: new TextStyle(
                  fontSize: 16.0, color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
person John Wiese    schedule 04.04.2018
comment
не решает проблему ... использование Expand в качестве родительского элемента для SingleChildScrollView отображает на экране заметку ... даже не изображение и текст заголовка вверху ... это дает следующую ошибку ... - person Vaibhav Miniyar; 04.04.2018
comment
Я добавил код, который у меня работает, для справки. - person John Wiese; 06.04.2018
comment
Большое спасибо тебе, @jhon Wiese ... Это сработало, но я все же не знаю, в чем именно ошибка, которую я делал .... в любом случае большое спасибо :) - person Vaibhav Miniyar; 06.04.2018
comment
@JohnWiese Идеально. - person H4ze; 22.12.2020

Если вы хотите коснуться любой части экрана и иметь возможность прокручивать, используйте этот пример. Я использовал желтый и зеленый цвета, чтобы показать, что будет прокручиваться весь экран, а не только текстовая область.

import 'package:flutter/material.dart';

class ShowFilePage extends StatefulWidget {
  @override
  _ShowFilePageState createState() => _ShowFilePageState();
}

class _ShowFilePageState extends State<ShowFilePage> {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
        backgroundColor: Colors.yellow,
        appBar: AppBar(
          title: Text('Text'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
                child: Container(
                    color: Colors.green,
                    child: SingleChildScrollView(child: Text('insert long text here')))),
          ],
        ));
  }
}
person live-love    schedule 09.01.2021

Для простоты используйте третий паб: Marquee

Marquee(
  text: 'There once was a boy who told this story about a boy: "',
)
person JerryZhou    schedule 14.01.2020
comment
Это дает мне ошибку, или, проще говоря, это не позволяет мне использовать рамку, независимо от того, что я использую контейнер, столбец и т. Д. - person An Android; 17.05.2021
comment
@AnAndroid, вы можете создать проблему на странице github этой библиотеки. - person JerryZhou; 19.05.2021
comment
Автор Marquee уже сказал, что он не работал над этим пакетом какое-то время, и теперь, поскольку большинство вещей новое / изменено, теперь он собирается обновить его (весь пакет, и ему нужно время для этого) , это все, что я знаю, поэтому я приехал сюда, чтобы узнать другой путь! Кстати, спасибо! - person An Android; 19.05.2021

Для вертикальной и горизонтальной прокрутки текста я использовал следующий код.

SingleChildScrollView(
    scrollDirection: Axis.vertical,
    child: SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Text('Your text.......')
    ),
  );
person Niraj Phutane    schedule 18.02.2021

Просто поместите корневой контейнер в виджет SingleChildScrollView ().

SingleChildScrollView(
  child: Container() // your root container
)
person Abdul Qadir    schedule 21.12.2020