Как решить, "RenderBox не был выложен:" во флаттере в виджете карты
У меня есть карточка с тремя контейнерами. Первые два имеют текст, а последний должен содержать TextFormField вместе с некоторым текстом. Так что у меня есть ряд, чтобы держать их вместе. Единственное, что, когда я добавляю виджет TextFormField, он не появляется, а в консоли выдает ошибку
══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY
╞═════════════════════════════════════════════════════════
I/flutter (14101): The following assertion was thrown during
performLayout():
I/flutter (14101): BoxConstraints forces an infinite width.
I/flutter (14101): These invalid constraints were provided to
RenderRepaintBoundary's layout() function by the
I/flutter (14101): following function, which probably computed the invalid
constraints in question:
I/flutter (14101): _RenderDecoration._layout.layoutLineBox
(package:flutter/src/material/input_decorator.dart:750:11)
I/flutter (14101): The offending constraints were:
I/flutter (14101): BoxConstraints(w=Infinity, 0.0<=h<=100.0)
I/flutter (14101): Another exception was thrown: RenderBox was not laid out:
RenderPadding#150b0 relayoutBoundary=up3 NEEDS-PAINT
I/flutter (14101): Another exception was thrown:
'package:flutter/src/rendering/shifted_box.dart': Failed assertion: line 310
pos 12: 'child.hasSize': is not true.
I/flutter (14101): Another exception was thrown: RenderBox was not laid out:
RenderPhysicalShape#1d998 relayoutBoundary=up4
Код выглядит так
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Card(
elevation: 2.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
height: 100.0,
color: Colors.purple,
),
Container(
height: 200.0,
color: Colors.pink,
child: Column(
children: <Widget>[
new RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: 'Some Text',
style: TextStyle(
color: Colors.grey[800],
fontWeight: FontWeight.bold,
fontSize: 17.0),
),
),
new RichText(
softWrap: true,
textAlign: TextAlign.center,
text: TextSpan(
text:
'Some other text',
style: TextStyle(
color: Colors.black54,
fontWeight: FontWeight.normal,
fontSize: 17.0),
),
),
Row(
children: <Widget>[
Text('adfa'),
Text('data'),
Form(
child: TextFormField(),
),
],
)
],
),
),
],
),
),
));
}
}
6 ответов
TextFormField
вызывает проблему. Нужны ограничения по ширине. Например, обернуть его в расширенный виджет или контейнер с шириной.
Причина ошибки:
Row
расширяется в горизонтальном направлении, как и TextField
, поэтому нам нужно ограничить ширину TextField
, вы можете попробовать любое из следующих действий.
Использовать
Expanded
Row( children: <Widget>[ Expanded(child: TextField()), ], )
Использовать
Flexible
Row( children: <Widget>[ Flexible(child: TextField()), ], )
Завернуть в
Container
илиSizedBox
и предоставитьwidth
Row( children: <Widget>[ SizedBox(width: 100, child: TextField()), ], )
Потратив много времени, я нашел решение, как показано ниже:
Пожалуйста, добавьте shrinkWrap: true
внутри ListView.builder()
.
Мне это помогло.
Я отвечаю на улучшение поста German Saprykin, я также получал ту же ошибку ниже
════════ (2) Исключение, обнаруженное при рендеринге библиотеки. TextField не может иметь неограниченную ширину. Это происходит, когда родительский виджет не обеспечивает ограничение конечной ширины. Например, если InputDecorator содержится в строке, его ширина должна быть ограничена. Виджет Expanded или SizedBox можно использовать для ограничения ширины InputDecorator или TextField, которое его содержит. 'package:flutter/src/material/input_decorator.dart': Неудачное утверждение: строка 910 поз. 7: 'layoutConstraints.maxWidth
════════ (3) Исключение, обнаруженное при рендеринге библиотеки. b1ce0 relayoutBoundary=up26 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE 'package:flutter/src/rendering/box.dart': Неудачное утверждение: строка 1681 pos 12: 'hasSize' Созданный пользователем предок вызывающего ошибку виджета был: TextField file:///C:/CommBack/My_Workplace/Flutter/wiremusic/wiremusic_dev/lib/wire/widgets/searchfield.dart:15:14 ══════════════════════════════════════════════════════════════════
из-за этого ниже более ранние исходные строки.
return Container(
color: Colors.yellow,
constraints: BoxConstraints(minWidth: 230.0, minHeight: 25.0),
child: TextField(),
);
потому что TextField требует предка hasSize
явно и после явного упоминания ширины в контейнере ошибка исчезла, как Thanos
return Container(
color: Colors.yellow,
width: 230,
constraints: BoxConstraints(minWidth: 230.0, minHeight: 25.0),
child: TextField(),
);
Надеюсь, это кому-то поможет.
если вы используете ListView.builder и получаете эту ошибку, то это решение
Использовать в построителе == shrinkWrap: true,
ListView.builder(
itemCount: historyList.length,
shrinkWrap: true, ///////////////////////Use This Line
itemBuilder: (BuildContext context, int index) {
return historyListItem(historyList[index]['text'], 60, () {}, false, size);
},
)
Перенос строки в виджет Expanded(). Его позволит ряду занять столько места, сколько он хочет занять