When working with a new version of Flutter(2.5.0 or higher), the IDE (like VS Code) will yell at you if you call the print() function to output something to the console (this behavior didn’t happen before):
Avoid `print` calls in production code
Screenshot:
Even though your app still works fine but the blue underline might be annoying and many developers will not be happy with it. There are several ways to get rid of this (without downgrading your Flutter SDK). Let’s explore them one by one.
Using debugPrint function
Instead of using the print() function, we call the debugPrint() function to display things in the console. Don’t forget to import package:flutter/foundation.dart or package:flutter/material.dart into your code:
import 'package:flutter/foundation.dart';
Screenshot:
Checking Debug Mode
You can call the print() function without the annoying blue warning by adding a check before calling it, like this:
// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
void main() {
if (kDebugMode) {
print('Hi there!');
}
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
/* ... */
}
Note that you have to import package:flutter/foundation.dart to use kDebugMode.
Screenshot:
Ignoring avoid_print (not recommended)
You can disable the warning for a Dart file by adding the following line to the very top of that file:
// ignore_for_file: avoid_print
Screenshot:
You can also disable the warning for a single line by inserting // ignore: avoid_print before using the print() function, like this:
Afterword
Flutter is rapidly evolving and many things change to force write better code and the print() function is a typical example. If you’d like to explore more new and exciting stuff in modern Flutter and Dart, take a look at the following articles:
- Flutter: Create a Password Strength Checker from Scratch
- SQLite: Select Random Records from a Table
- Prevent VS Code from Auto Formatting Flutter/Dart Code
- Flutter: Drawing an N-Pointed Star with CustomClipper
- Flutter: FilteringTextInputFormatter Examples
- Hero Widget in Flutter: A Practical Guide
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.