Michael Frischbutter
Michael Frischbutter

Michael Frischbutter

How do you use the print statements in Flutter effectively

Photo by Shirley Cairns on Unsplash

How do you use the print statements in Flutter effectively

Michael Frischbutter's photo
Michael Frischbutter
·Jan 12, 2022·

2 min read

Table of contents

  • print() & debugPrint() are visible in Logcat in production
  • How to use colorful print statements in VS Code

We all use print() or debugPrint() on a daily basis in Flutter. Whether it's to track the appflow in the console, or just to keep an eye on the status of certain services. In this short article I want to talk about what all is possible with print() or debugPrint(), or you should be aware of.

print() & debugPrint() are visible in Logcat in production

What many people don't know, or I haven't realized for a long time, is that print statements can also be read in the release build or in your app with Logcat. This can be a problem if sensitive data is printed in some places.

How can I fix this?

For debugPrint()

void main {
    // Dont print debugPrint() statements in production
    if (kReleaseMode) {
        debugPrint = (String? message, {int? wrapWidth}) {};
    }
}

For print() you have to do this instead of just runApp(MyApp())

import 'dart:async';

void main() {
  runZonedGuarded(
    () {
      runApp(const MyApp());
    },
    (error, stackTrace) {
      print(error);
    },
    zoneSpecification: ZoneSpecification(
      print: (Zone self, ZoneDelegate parent, Zone zone, String message) {
        // Dont print print() statements in production
        if (kDebugMode) {
          parent.print(zone, message);
        }
      },
    ),
  );
}

After that you are still able to see the log messages in debug mode but not in production mode.

How to use colorful print statements in VS Code

Sometimes you want to distinguish certain outputs from each other. There is a solution for this, colors or emojis!

Colored print output (Not working for Android Studio yet).

void printWarning(String text) {
  print('\x1B[33m$text\x1B[0m');
}

void printError(String text) {
  print('\x1B[31m$text\x1B[0m');
}

Add Emojis to your debug messages

/// printWarning('message') -> ⚠️ message
void printWarning(String text) {
  print('⚠️ $text');
}
/// printError('message') -> ❗ message
void printError(String text) {
  print('❗ $text');
}

And thats it for now. Thank you for reading till the end and i hope you learned something new. emoji gif

 
Share this