Search code examples
flutterflutter-layoutcross-platform

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


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.


Solution

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