gpt4 book ai didi

Flutter - 自动调整 AlertDialog 大小以适应列表内容

转载 作者:IT王子 更新时间:2023-10-29 06:35:40 31 4
gpt4 key购买 nike

我需要从 rest web 服务动态加载列表城市,并让用户从警报对话框中选择一个城市。我的代码:

createDialog() {

fetchCities().then((response) {

showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Wybierz miasto'),
content: Container(
height: 200.0,
width: 400.0,
child: ListView.builder(
shrinkWrap: true,
itemCount: response.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(response[index].name),
onTap: () => citySelected(response[index].id),
);
},
),
),
);
}
);
});
}

结果 - 对话框始终为 200x400,即使只有 2 个城市可用,底部也会留下不必要的空间:

enter image description here

如何使对话框宽度/高度适合实际项目大小?如果我省略 heightwidth 参数,我会遇到异常并且不会显示对话框。在 native Android Java 中,我从不需要指定任何尺寸,因为对话框会自动调整自身大小以适应。

如何修复我的代码以正确调整对话框大小?注意:我不知道项目数,它是动态的。

[编辑]

按照建议,我用列包装了内容:

createDialog() {
fetchCities().then((response) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Wybierz miasto'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: response.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(response[index].name),
onTap: () => citySelected(response[index].id),
);
},
),
)
]
),
);
}
);
});
}

结果 - 异常:

I/flutter ( 5917): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY╞═════════════════════════════════════════════════════════ I/flutter (5917): The following assertion was thrown during performLayout():I/flutter ( 5917): RenderViewport does not support returning intrinsicdimensions. I/flutter ( 5917): Calculating the intrinsic dimensionswould require instantiating every child of the viewport, whichI/flutter ( 5917): defeats the point of viewports being lazy.

要测试的更通用的代码:

showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Select city'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: 2,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text("City"),
onTap: () => {},
);
},
),
)
]
),
);
}
);

最佳答案

将您的 Container 包裹在 Column 中,在内容参数中,在其中设置 mainAxisSize.min,在 Column 属性中

Container(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...
],
)
)

关于Flutter - 自动调整 AlertDialog 大小以适应列表内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54669630/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com