Flutter Reaches 2.0

Flutter Reaches 2.0
Flutter Logo

Compiling Legacy Dart/Flutter Code with Sound Null Safe Code

Anyone who knows me knows how I feel about flutter, Googles (fairly) new cross-platform toolkit. I started working with flutter back in 2017 and it has been a lot of fun! This past week Google held a virtual event for flutter called Flutter Engage. During the event, the flutter team announced that Flutter was now 2.0. Mostly this new version brings with it a stable web implementation and null safety. However, there are also a few new widgets for us flutter developers to toy with.

As soon an I learned of Flutter 2’s null safety features I had to try them. I took an older application from my archive and changed the pubspec.yaml file to require 2.12.0 or above and compiled the app. Most files complied without error, except for one of my custom libraries. It game me an error telling me to change the language version. The error occurred on every use of the ? operator in my code.

I was looking for a solution in the command line arguments when I saw that Randal Schwartz had posted a video in the Flutter Slack channel about this very issue. Randal discovered, as I did, that combining legacy code (pre-2.12) and sound null safety code causes compilation to fail. He demonstrated a command line argument for dart to allow all the code to be compiled without the sound null safety features. The command Randal used was:

$ dart --no-sound-null-safety <program_name>

This will not work when using your IDE to build the project. Anyone using Android Studio has undoubtedly learned that you can pass command-line arguments to the compiler in the Settings->Build->Compiler->Command-line Options field. Under VS Code (another popular IDE for Flutter devs), you can go to the hidden .vscode directory in your project and make changes to your settings.json file. Here you’ll want to add or modify two sections. Most likely, your settings file will be empty. Mine contains a path to my default Python compiler because I also use VS Code to develop python projects. For smaller projects, it is my favorite IDE. Here is my settings.json file:

{
    "python.pythonPath": "/usr/bin/python3.8"
}

In this file we want to add two new settings as follows:

{
    "python.pythonPath": "/usr/bin/python3.8",

    "dart.flutterAdditionalArgs": [
        "--no-sound-null-safety"
    ],

    "dart.vmAdditionalArgs": [
        "--no-sound-null-safety"
    ]
}

Be sure to add a comma after any settings that already exists in the file, like I did here after the python.pythonPath value. Once you save this you should be able to use VS Code’s run configurations to compile and run your project.

Here’s a link to Randal Schwartz’s video that may help you: https://www.youtube.com/watch?v=_Nvt_Du7H3I

Leave a Reply

Your email address will not be published. Required fields are marked *