我需要帮助来了解为什么Rows
,Columns
和Expanded
在这种布局中需要有限的宽度约束。
在我看来,布局非常简单:两列应平均划分设备总宽度,每列中必须有一个固定的宽度标签和一个文本字段,该文本字段应占用剩余的列宽:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Row(
children: [
Column(
children: [
Row(children: [
Text('Field 1:'),
Expanded(
child: TextField(),
),
]),
],
),
Column(
children: [
Row(children: [
Text('Field 2:'),
Expanded(
child: TextField(),
),
]),
],
),
],
),
),
),
);
}
我当然会收到此错误:
flutter: The following assertion was thrown during performLayout():
flutter: RenderFlex children have non-zero flex but incoming width constraints are unbounded.
flutter: When a row is in a parent that does not provide a finite width constraint, for example if it is in a
flutter: horizontal scrollable, it will try to shrink-wrap its children along the horizontal axis. Setting a
flutter: flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
flutter: space in the horizontal direction.
[...]
避免设置固定宽度的列并扩展其工作的最佳策略是什么?
编辑:
我更改了将Column
小部件包装在Expanded
小部件内的代码。
做到了,此代码不会引发错误:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Row(
children: [
Expanded(
child: Column(
children: [
Row(children: [
Text('Field 1:'),
Expanded(
child: TextField(),
),
]),
],
),
),
Expanded(
child: Column(
children: [
Row(children: [
Text('Field 2:'),
Expanded(
child: TextField(),
),
]),
],
),
),
],
),
),
),
);
}
答案 0 :(得分:0)
由于TextField
试图占据整个宽度而引发错误。
按照this answer给出的说明,将TextField
用Flexible
包装。
import 'package:flutter/material.dart';
class SO62977964 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.blueGrey),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('SO 62977964'),
),
body: Row(
children: [
Expanded(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Flexible(
child: Text('Field 1'),
),
Flexible(
child: TextField(
decoration:
InputDecoration(hintText: 'Enter Field 1'),
),
),
],
),
],
),
),
Expanded(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Flexible(
child: Text('Field 2'),
),
Flexible(
child: TextField(
decoration:
InputDecoration(hintText: 'Enter Field 2'),
),
),
],
),
],
),
),
],
),
),
);
}
}