TextButton 小部件宽度的变化取决于 Row 小部件

问题描述 投票:0回答:1

当我将 TextButton 小部件放置在 Row 小部件内时,TextButton 小部件的宽度会缩小,我无法理解其原因。

class DrumMachine extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Column(
            children: [
              TextButton(
                onPressed: () {
                  print("f");
                },
                child: Container(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在我编写的代码中,当使用“切换选择小部件模式”设置从模拟器查看时,TextButton 小部件的宽度显示如下:

没有行小部件的代码

但是,当我将 TextButton 小部件放置在 Row 小部件内时,TextButton 小部件的宽度显示如下:

使用行小部件进行编码

代码如下:

class DrumMachine extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Column(
            children: [
              Row(
                children: [
                  TextButton(
                    onPressed: () {
                      print("f");
                    },
                    child: Container(),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这段代码中,Row部件的宽度处于最大尺寸,即与第一段代码中TextButton部件的宽度相同,我可以理解这一点。但是,我无法理解为什么在此代码中 TextButton 小部件不像第一个代码中那样保持最大宽度(等于 Row 小部件的宽度),而是缩小了。这是什么原因呢?

Row widget 的大小如下,最大宽度:

行小部件的大小

flutter dart
1个回答
0
投票

您需要将 TextButton 包装在 Expanded 中,Expanded 将使用所有可用的行空间

class DrumMachine extends StatelessWidget {
  const DrumMachine({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.purple),
                        shape: MaterialStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(0),
                          ),
                        ),
                      ),
                      onPressed: () {
                        print("f");
                      },
                      child: Container(),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.