英文:
How to use Expanded and a Container with a fixed height together in a column without overflow
问题
以下是您要翻译的代码部分:
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('TestApp')),
    body: Column(
      children: [
        Container(
          height: 100,
          color: Colors.red,
        ),
        Expanded(
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}
通常情况下,没有问题,但当屏幕的高度小于100时,会发生溢出。我希望高度不会溢出,而是减小。
我尝试过使用SingleChildScrollView和Wrap,然后Expanded不可用。并且使用ConstrainedBox来设置MaxHeight为100,仍然会发生溢出。
英文:
Simply put, I want the following code to run without overflow.
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('TestApp')),
    body: Column(
      children: [
        Container(
          height: 100,
          color: Colors.red,
        ),
        Expanded(
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}
Normally, there is no problem, but when the height of the screen is smaller than 100, overflow happens. Instead of overflowing, I want the height to be reduced.
I tried SingleChildScrollView and Wrap, and then Expanded was unavailable.And using ConstrainedBox to set MaxHeight to 100, still, there was an overflow.
答案1
得分: 0
你可以使用MediaQuery类来避免使用LayoutBuilder。
@override
Widget build(BuildContext context) {
  final screenHeight = MediaQuery.of(context).size.height;
  final minHeight = 100;
  return Scaffold(
    body: Column(
      children: [
        Container(
          height: screenHeight < minHeight ? screenHeight : 100,
          color: Colors.red,
        ),
        Expanded(
          flex: screenHeight < minHeight ? 0 : 1,
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}
英文:
You can take aid of MediaQuery class,  if you want to avoid LayoutBuilder
@override
Widget build(BuildContext context) {
  final screenHeight = MediaQuery.of(context).size.height;
  final minHeight = 100;
  return Scaffold(
    body: Column(
      children: [
        Container(
          height: screenHeight < minHeight  ? screenHeight : 100,
          color: Colors.red,
        ),
        Expanded(
          flex: screenHeight < minHeight  ? 0 : 1,
          child: Container(
            color: Colors.blue,
          ),
        )
      ],
    ),
  );
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论