Search code examples
flutteruser-interfacerenderinginteractive

Making a widget stateful causing hasSize exception


The following page widget throws the exception `'package:flutter/src/rendering/box.dart': box.dart:1 Failed assertion: line 1965 pos 12: 'hasSize'

The relevant error-causing widget was Scaffold

Failed assertion: line 1965 pos 12: 'hasSize'

The relevant error-causing widget was FittedBox`

However as soon as I make the widget stateless or remove the FittedBox widget, the run time error goes away.


class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  String _result = '';

  @override
  Widget build(BuildContext context) {
    Widget result = FittedBox(
      child: Text(_result),
    );

    Widget actionButton = ElevatedButton(
      onPressed: () {
        setState(() {
          _result = 'Text generated';
        });
      },
      child: const Text('Press me'),
    );

    Widget bottom = Container(
      height: 80,
      color: Colors.orange,
      alignment: Alignment.center,
      child: const Text("Footer"),
    );

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('My App'),
      ),
      body: Padding(
        padding: const EdgeInsets.only(top: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            const Flexible(
              flex: 15,
              child: TextField(),
            ),
            Expanded(
              flex: 10,
              child: result,
            ),
            Container(
              height: 50,
              child: Text('Somre data'),
            ),
            const Expanded(
              flex: 56,
              child: Text('Some content'),
            ),
            bottom,
          ],
        ),
      ),
    );
  }
}

I am encountring a situation where the output result can be upto 30 characters long. I want the result content to be shown on a single line and of maximum size while following the constraints specified by flex properties.


Solution

  • The solution is to specify a width for the result widget through a container.

    Expanded(
        flex: 10,
        child: result,
    ),
    

    Update the above code to

    Expanded(
        flex: 10,
        child: Container(
            width: screenWidth,
            child: result,
        ),
    ),
    

    Where screenWidth is taken through media query.