Flutter: невозможно добавить ListView в пример приложения - PullRequest
0 голосов
/ 26 апреля 2020

Мне трудно найти выход из этого положения. Я создал приложение Flutter по умолчанию, которое поставляется с учебником basi c, и теперь я хотел бы добавить к нему ListView, например:

  body: Center(
    // Center is a layout widget. It takes a single child and positions it
    // in the middle of the parent.
    child: Column(
      // Column is also a layout widget. It takes a list of children and
      // arranges them vertically. By default, it sizes itself to fit its
      // children horizontally, and tries to be as tall as its parent.
      //
      // Invoke "debug painting" (press "p" in the console, choose the
      // "Toggle Debug Paint" action from the Flutter Inspector in Android
      // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
      // to see the wireframe for each widget.
      //
      // Column has various properties to control how it sizes itself and
      // how it positions its children. Here we use mainAxisAlignment to
      // center the children vertically; the main axis here is the vertical
      // axis because Columns are vertical (the cross axis would be
      // horizontal).
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          'You have pushed the button this many times:',
        ),
        Text(
          '$_counter',
          style: Theme.of(context).textTheme.display1,
        ),
        ListView(
          padding: const EdgeInsets.all(8),
          children: <Widget>[
            Container(
              width: 50, // This changes nothing. 
              height: 50, // This changes nothing.
              child: const Center(child: Text('Text entry'))
            )
          ]
        ),
      ],
    ),
  ),

Единственное, что я добавил, это виджет ListView.

Я получаю следующую ошибку:

════════ Exception caught by rendering library ═════════════════════════════════════════════════════
RenderBox was not laid out: RenderRepaintBoundary#d4bf6 relayoutBoundary=up3 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1687 pos 12: 'hasSize'
The relevant error-causing widget was: 
  Column file:///Users/user/code/project/lib/main.dart:77:16
════════════════════════════════════════════════════════════════════════════════════════════════════

Теперь я пришел к выводу, что это как-то связано с упаковкой ListView в родительский контейнер. , возможно, что движок рендеринга не знает, как обрабатывать размер представления списка, но я не смог найти информацию о том, как на самом деле это исправить.

Ответы [ 3 ]

1 голос
/ 26 апреля 2020

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

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

1 голос
/ 26 апреля 2020

это потому, что ListView по умолчанию хочет расширить себя, чтобы заполнить доступное пространство. и заставит вас обернуть его столбцом, он не сможет расшириться. у вас есть два варианта здесь:

  1. Во-первых, это обернуть ваш список с расширенным виджетом. Расширение займет все оставшееся доступное пространство для его дочернего элемента. для этой опции используйте код ниже:
Expanded(
  child: ListView(
    padding: const EdgeInsets.all(8),
    children: <Widget>[
      Container(
        width: 50, // This changes nothing.
        height: 50, // This changes nothing.
        child: const Center(child: Text('Text entry'))
      )
    ]
  ),
),
второй вариант - установить для свойства shrinkWrap объекта ListView значение true. делая это ListView, не расширяйте себя:
ListView(
  shrinkWrap: true,
  padding: const EdgeInsets.all(8),
  children: <Widget>[
    Container(
      width: 50, // This changes nothing.
      height: 50, // This changes nothing.
      child: const Center(child: Text('Text entry'))
    )
  ]
)
1 голос
/ 26 апреля 2020

listView имеет атрибут shrinkWrap, вы можете попробовать:

ListView(
  shrinkWrap: true,
  padding: const EdgeInsets.all(8),
  children: <Widget>[
    Container(
      width: 50, // This changes nothing.
      height: 50, // This changes nothing.
      child: const Center(child: Text('Text entry'))
    )
  ]
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...