Как передать несколько виджетов в качестве дочерних элементов во Flutter?

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

Всякий раз, когда я передаю RaisedButton с виджетом ListView в другой виджет ListView или Column, возникает ошибка.

I/flutter ( 4734): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4734): The following assertion was thrown during performResize():
I/flutter ( 4734): Vertical viewport was given unbounded height.
I/flutter ( 4734): Viewports expand in the scrolling direction to fill their container.
////MORE LINES OF ERRORS/////

Вот код, над которым я работал:

import 'package:flutter/material.dart';

void main() {
  runApp(ListDemo(
    items: new List<ListItem>.generate(
      100,
          (i) => i % 6 == 0
          ? new HeadingItem("Heading $i")
          : new MessageItem("Sender $i", "Message body $i"),
    ),
  ));
}

// The base class for the different types of items the List can contain
abstract class ListItem {}

// A ListItem that contains data to display a heading
class HeadingItem implements ListItem {
  final String heading;

  HeadingItem(this.heading);
}

// A ListItem that contains data to display a message
class MessageItem implements ListItem {
  final String sender;
  final String body;

  MessageItem(this.sender, this.body);
}

class ListDemo extends StatelessWidget {
  final List<ListItem> items;
  ListDemo({Key key, @required this.items}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final ListView listView = ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        final item = items[index];

        if (item is HeadingItem) {
          return new ListTile(
            title: new Text(
              item.heading,
              style: Theme.of(context).textTheme.headline,
            ),
          );
        } else if (item is MessageItem) {
          return new ListTile(
            title: new Text(item.sender),
            subtitle: new Text(item.body),
          );
        }
      },
    );

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Lists'),
        ),
        body: ListView( //Tried using ListView, Column.. None of them help solving the issue
          children: <Widget>[
            RaisedButton(
              onPressed: null,
              child: Text('Sample Button'),
            ),
            Container(
              child: listView,
            )
        ]
      )
      )
    );
  }
}

Пожалуйста, помогите мне решить эту проблему, сообщая, как передать несколько детей, а также, пожалуйста, поймите концепцию.

ОТРЕДАКТИРОВАНО

Одно из возможных решений предложило обернуть ListView классом Expanded. Когда я это сделал, это выдало мне ошибку, как показано ниже:

I/flutter ( 4190): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 4190): The following assertion was thrown building NotificationListener<KeepAliveNotification>:
I/flutter ( 4190): Incorrect use of ParentDataWidget.
I/flutter ( 4190): Expanded widgets must be placed inside Flex widgets.
I/flutter ( 4190): Expanded(no depth, flex: 1, dirty) has no Flex ancestor at all.

Поэтому я завернул весь код виджета в Flex, как показано ниже:

      Flex(
        direction: Axis.vertical,
        children: <Widget>[
          ListView(
            children: <Widget>[
              RaisedButton(
               onPressed: null,
               child: Text('Snackbar'),
              ),
              Expanded(
               child: listView
              )
             ],
            )
          ],
        )

но потом он выдал мне эту ошибку:

I/flutter ( 4388): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4388): The following assertion was thrown during performResize():
I/flutter ( 4388): Vertical viewport was given unbounded height.
I/flutter ( 4388): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 4388): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 4388): typically happens when a scrollable widget is nested inside another scrollable widget.

person starlight    schedule 05.06.2018    source источник
comment
@RémiRousselet Предложенное там решение, похоже, мало помогает.   -  person starlight    schedule 05.06.2018
comment
Старлайт, ты мой герой. Хотя Flex( direction: Axis.vertical, children: <Widget>[... не сработало для вас, это исправление полностью сработало для меня. Многие спасибо.   -  person zipzit    schedule 15.08.2018


Ответы (1)


Здесь уже есть ответ на этот вопрос

Не удается добавить ListView во Flutter

Если вы используете scrollable view(Listview) inside another scrollable view, inner scrollable view не знает how much height it should occupy. Вы можете сообщить внутреннему прокручиваемому представлению, какую высоту оно должно занимать, с помощью виджета Expanded.

person Vinoth Kumar    schedule 05.06.2018
comment
Если на этот вопрос уже был дан ответ, отметьте его как дубликат вместо повторного ответа. - person Rémi Rousselet; 05.06.2018
comment
Он попросил объяснить, почему это происходит. Там я не давал никаких пояснений. Вот почему я добавил это как ответ - person Vinoth Kumar; 05.06.2018
comment
Но вы можете отредактировать свой исходный ответ, указав дополнительную информацию, а затем пометить его как дубликат. Как правило, вопросы считаются дубликатами, если на них один и тот же ответ. - person Rémi Rousselet; 05.06.2018
comment
@VinothKumar Решение, похоже, не решает проблему полностью, оно вызывает новую ошибку. Я поместил реализацию и ошибки, вызванные в отредактированной части выше. - person starlight; 05.06.2018
comment
Почему вы не можете использовать Column вместо ListView? Есть какая-то конкретная цель? - person Vinoth Kumar; 05.06.2018
comment
@VinothKumar Когда я использую ColumnView, RaisedButton остается фиксированным вверху, и прокручивается только ListView. Я хотел бы, чтобы весь экран был прокручиваемым. - person starlight; 05.06.2018