我是Flutter / Dart的新手,所以也许我遇到的问题仅仅是缺乏知识。我的目标是构建一个在卡的顶部具有水平标题的卡,然后该卡应垂直显示项目/值对的列表,如果设备足够大,则将它们包装到新列中。我添加了一个专栏,用于两个子项(标头和Wrap),但是如果将其嵌入在专栏中,则根本没有包装。
我尝试了很多组合,但没有找到解决方案。如果我删除了该列,则“包裹”小部件会正常工作。
class TestApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return
MaterialApp(
title: 'Wrap Test',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: TestScreen(),
);
}
}
class TestScreen extends StatelessWidget {
/*
Builds a single item/value pair
*/
Widget _text(int i) {
var container = Container(
height: 50,
child: Row(
children: <Widget>[
Container(
width: 200,
child: Text(
'item $i',
),
),
Text(
'value $i',
),
],
),
);
return container;
}
/*
Builds a list of item/value pairs
*/
List<Widget> _items(int n) {
List<Widget> widgetList = [];
for (int i = 1; i <= n; i++) {
widgetList.add(_text(i));
}
return widgetList;
}
/*
This way Wrap widget isn't working as I thought...the reason is that it seems bounded by
the column and the column does not expands itself due to wrapping
*/
Widget buildWrapNotWorking(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Wrap Test"),
),
body: Card(
color: Colors.yellow,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Header",
),
Wrap(
direction: Axis.vertical,
runSpacing: 50,
crossAxisAlignment: WrapCrossAlignment.start,
spacing: 20,
children: _items(20),
),
],
),
),
);
}
/*
This way Wrap widget is working, because I removed the column. But I need to have a card header
on top of the card.
*/
Widget buildWrapWorkingButNoHeader(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Wrap Test"),
),
body: Card(
color: Colors.yellow,
child: Wrap(
direction: Axis.vertical,
runSpacing: 100,
crossAxisAlignment: WrapCrossAlignment.start,
spacing: 20,
children: _items(20),
),
),
);
}
@override
Widget build(BuildContext context) {
return buildWrapNotWorking(context);
// return buildWrapWorkingButNoHeader(context);
}
}
我希望调用buildWrapNotWorking(context)将按需要工作。
问题类似于那个问题: How to wrap row items in a card with flutter
答案 0 :(得分:1)
只需用Wrap
包装Expanded
小部件-这是因为它将在列中获得足够的空间。
代码:
Widget buildWrapNotWorking(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Wrap Test"),
),
body: Card(
color: Colors.yellow,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Header",
),
Expanded(
child: Wrap(
direction: Axis.vertical,
runSpacing: 50,
crossAxisAlignment: WrapCrossAlignment.start,
spacing: 20,
children: _items(20),
),
),
],
),
),
);
}