为什么ElevatedButton被拉伸以适应屏幕宽度?

3
这是屏幕部分的完整代码:
ListView(children: [
  ClipRect(
    child: Image.asset(
      'images/icon.png',
      scale: 2,
    ),
  ),
  Padding(
    padding: const EdgeInsets.symmetric(horizontal: 24.0),
    child: TextField(
      controller: _word,
      textAlign: TextAlign.center,
      decoration: InputDecoration(
        filled: true,
        helperText: 'Enter a word',
      ),
    ),
  ),
  Padding(
    padding: const EdgeInsets.only(top: 20, left: 24, right: 24, bottom: 8),
    child: ElevatedButton(
        child: Text("Search!"),
        onPressed: () async {
          String word = _word.text;
          _word.text = '';
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return word == '' ? RandomResults() : Results(word);
          }));
        }),
  ),
]),

然而结果看起来像这样: 图片 我已经尝试使用MaterialButton替代ElevatedButton,但它也会被拉伸以适应屏幕的宽度。
我想让按钮足够大,能够容纳内部的文本。
3个回答

2
将按钮包裹在 Center 中(或者如果您想以不同的位置放置它,则可以选择 Align)。
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Center(
          child: ElevatedButton(
            onPressed: () {},
            child: Text('Search!'),
          ),
        ),
      ],
    );
  }

0

row进行包装

 Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ElevatedButton(
                    child: Text("Search!"),
                    onPressed: () async {
                      // String word = _word.text;
                      // _word.text = '';
                      // Navigator.push(context, MaterialPageRoute(builder: (context) {
                      //   return word == '' ? RandomResults() : Results(word);
                      // },),);
                    }),
              ],
            ),

```

3
尽可能避免使用将单个小部件包装为呈现多个子项的小部件,这不是一个好的做法。 - eeqk

0
将您的按钮放入一个SizedBox中,并设置所需的宽度:
SizedBox(width: MediaQuery.of(context).size.width * 0.50), 
         child: ElevatedButton(....)

这将使其宽度为屏幕的50%,您可以通过更改0.50比例来更改宽度。


这个会生成一个错误:已经指定了命名参数'child'的参数。 - Shourya Shikhar
1
这不行,按钮仍然填满了屏幕。 - eeqk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接