flutter даёт ошибку, нет контента на странице
При запуске этого кода происходит ошибка, буду очень благодарен тому, кто поможет
import 'package:flutter/material.dart';
void main() {
runApp(ChooseDomain());
}
String name = ".md";
int x = 0;
String valute = "MDL";
int y = 0;
String tick = "❌";
class ChooseDomain extends StatelessWidget {
void restart() => runApp(ChooseDomain());
@override
Widget build(BuildContext context){
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Выберите домен'),
backgroundColor: Colors.blue,
),
body: Column(
children: <Widget>[
Container(
color: Colors.grey,
child: Row(
children: <Widget>[
TextButton(
child: Text('$tick Зарегистрировать новый домен'),
onPressed:(){
tick = "✅";
restart();
}
),
TextButton(
child: const Text('www.'),
onPressed: () {
String a = "NONE";
}
),
TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Введите название домена',
),
),
TextButton(
child: Text(name),
onPressed: (){
//List<String> names = ['.md','.com','.ru','.org'];
if(x==0){
name = ".com";
x++;
restart();
}
else if(x==1){
name = ".ru";
x++;
restart();
}
else if(x==2){
name = ".org";
x++;
restart();
}
else if(x==3){
name = ".md";
x = 0;
restart();
}
}
),
TextButton(
child: Text(valute),
onPressed: (){
if(y==0){
valute = "EUR";
y++;
restart();
}
else if(y==1){
valute = "RUB";
y++;
restart();
}
else if(y==2){
valute = "USD";
y = 0;
restart();
}
}
)
]
)
)
]
)
)
);
}
}
Ответы (1 шт):
О чем ошибка
Вставил код
получил следующее:
An InputDecorator, which is typically created by a TextField, cannot have an unbounded width.
This happens when the parent widget does not provide a finite width constraint. For example, if the InputDecorator is contained by a Row, then its width must be constrained. An Expanded widget or a SizedBox can be used to constrain the width of the InputDecorator or the TextField that contains it.
'package:flutter/src/material/input_decorator.dart': Failed assertion: line 910 pos 7: 'layoutConstraints.maxWidth < double.infinity'
Там говориться о том, что InputDecorator не может иметь ограниченной ширины
И данный виджет не может использоваться вместе с родительскими элементами с неограниченной шириной. В частности там говориться о наиболее частом кейсе - использовании InputDecorator внутри Row который не ограничен по ширине.
Отсюда и ошибка.
Далее можно увидеть и ошибку рендеринга:
RenderObject: _RenderColoredBox#0bd33 relayoutBoundary=up2
needs compositing
parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
constraints: BoxConstraints(0.0<=w<=392.7, 0.0<=h<=Infinity)
size: MISSING
Она также указывает на то, что размер не указан size: MISSING
Что с этим делать?
Одним из вариантов является обернуть все необходимые элементы виджетом Expanded
Задача данного виджета заполнять имеющееся в распоряжении пространство
https://api.flutter.dev/flutter/widgets/Expanded-class.html
Expanded(
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Введите название домена',
),
))
Чтобы избежать вышеуказанных ошибок будет достаточно обернуть виджет в котором используется InputDecoration()
Однако, после использования Вы сразу столкнетесьс другой ошибкой, связанной с шириной.

Она(ширина) хоть будет и не бесконечная, но все равно будет выходить за рамки экрана.
Тут я сильно мудрить не стал и просто вставил два символа перехода строки(\n) в текст кнопки.
Ну и обернул их виджетом Center для выравнивания текста по центру
child: Center(
child: Text(
'$tick Зарегистрировать\nновый\nдомен',
textAlign: TextAlign.center,
),
),
Минимальный рабочий пример:
import 'package:flutter/material.dart';
void main() {
runApp(ChooseDomain());
}
String name = ".md";
int x = 0;
String valute = "MDL";
int y = 0;
String tick = "❌";
class ChooseDomain extends StatelessWidget {
void restart() => runApp(ChooseDomain());
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Выберите домен'),
backgroundColor: Colors.blue,
),
body: Column(children: <Widget>[
Container(
color: Colors.grey,
child: Row(children: <Widget>[
TextButton(
child: Center(
child: Text(
'$tick Зарегистрировать\nновый\nдомен',
textAlign: TextAlign.center,
),
),
onPressed: () {
tick = "✅";
restart();
}),
TextButton(
child: const Text('www.'),
onPressed: () {
String a = "NONE";
}),
Expanded(
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Введите название домена',
),
)),
TextButton(
child: Text(name),
onPressed: () {
//List<String> names = ['.md','.com','.ru','.org'];
if (x == 0) {
name = ".com";
x++;
restart();
} else if (x == 1) {
name = ".ru";
x++;
restart();
} else if (x == 2) {
name = ".org";
x++;
restart();
} else if (x == 3) {
name = ".md";
x = 0;
restart();
}
}),
TextButton(
child: Text(valute),
onPressed: () {
if (y == 0) {
valute = "EUR";
y++;
restart();
} else if (y == 1) {
valute = "RUB";
y++;
restart();
} else if (y == 2) {
valute = "USD";
y = 0;
restart();
}
})
]))
])));
}
}
И как итог
Ну а по-хорошему все это нужно нормально сверстать не в одну строку а в несколько

