7 C
New York
Saturday, December 2, 2023

Flutter: Avoid `print` calls in production code

When working with a new version of Flutter(2.5.0 or higher), the IDE 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


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).

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';


Checking Debug Mode

AdvertisementsYou 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.


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


You can also disable the warning for a single line by inserting // ignore: avoid_print before using the print() function, like this:


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:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Related Articles

Latest Articles