Why is ElevatedButton getting stretched to fit the width of the screen?

Viewed 279

This is the full code of the screen's section:

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);
          }));
        }),
  ),
]),

However the result looks like this: image

I have tried using MaterialButton instead of ElevatedButton but it too gets dragged to fit the width of the screen.

I want to make the button just large enough to fit the text inside it.

3 Answers

Wrap the button with Center (or alternatively with Align if you want to position it differently)

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Center(
          child: ElevatedButton(
            onPressed: () {},
            child: Text('Search!'),
          ),
        ),
      ],
    );
  }

wrap with 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);
                      // },),);
                    }),
              ],
            ),

```

Wrap your button in a sized box and give it the width you want:

SizedBox(width: MediaQuery.of(context).size.width * 0.50), 
         child: ElevatedButton(....)

This will give it a width of 50% of the screen, you can change this by changing the 0.50 ratio.

Related