Fix: Argument contained a NaN value

Understanding and Solving the “Argument contained a NaN value” Error in Flutter

The “argument contained a NaN value” error is a common issue that Flutter developers encounter when using the LayoutBuilder widget. This error occurs when the constraints.maxWidth value passed to the LayoutBuilder is either NaN (Not a Number) or infinity.

Probable Causes

  • The constraints.maxWidth value may be NaN if the LayoutBuilder is used in an initial layout pass before the constraints are properly established.

  • If the constraints.maxWidth value is infinity, it may be due to an unexpected behavior in the layout calculation or a bug in the code.

Solutions

  • Wrap the LayoutBuilder widget in a WidgetsBindingObserver and listen for the didChangeMetrics event to ensure that the constraints are properly established before calculating the layout.
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WidgetsBindingObserver(
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          if (constraints.maxWidth.isInfinite || constraints.maxWidth.isNaN) {
            return Container();
          }

          // your layout code here
        },
      ),
      onDidChangeMetrics: (_) {
        setState(() {});
      },
    );
  }
}

Use the if statement to check if the constraints.maxWidth value is NaN or infinity and return an empty Container widget if it is.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        if (constraints.maxWidth.isInfinite || constraints.maxWidth.isNaN) {
          return Container();
        }

        // your layout code here
      },
    );
  }
}


Conclusion

The “argument contained a NaN value” error is a common issue when using the LayoutBuilder widget in Flutter, but it can be easily solved by using either the WidgetsBindingObserver or the if statement to ensure that the constraints are properly established and the constraints.maxWidth value is not NaN or infinity. By following these solutions, you can prevent this error and ensure a smooth and error-free development experience in Flutter.

Comments

  1. Very useful advice. As soon as I read it, it did occur to me that I was defaulting a widget size to Size.infinity. Many thanks. Much appreciated.

    ReplyDelete

Post a Comment