Fixing data != null is not true

Last reviewed by Frank Treacy
with Flutter 1.7.8

Getting 'data != null': is not true error?

It’s because you haven’t initialized a variable. Let’s have a look at this failing example:

class TestsScreen extends StatefulWidget {
  @override
  _TestsScreenState createState() => _TestsScreenState();
}

class _TestsScreenState extends State<TestsScreen> {

  bool _switchValue;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: CupertinoSwitch(
        value: _switchValue,
        onChanged: (bool value) {
          setState(() {
            _switchValue = value;
          });
        },
      )
    );
  }
}

Giving a default value to _switchValue will assign a default state to the button. And that fixes the issue.

class TestsScreen extends StatefulWidget {
  @override
  _TestsScreenState createState() => _TestsScreenState();
}

class _TestsScreenState extends State<TestsScreen> {

  bool _switchValue = false;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: CupertinoSwitch(
        value: _switchValue,
        onChanged: (bool value) {
          setState(() {
            _switchValue = value;
          });
        },
      )
    );
  }
}

The best from the Flutter-verse in 3 minutes or less? Join Snacks!

Delivered twice monthly. No link walls. No spam. EVER.