Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify the `print` function in Dart?

The print function is defined in both these files:

flutter/bin/cache/pkg/sky_engine/lib/core/print.dart

flutter/bin/cache/dart-sdk/lib/core/print.dart

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I opened each of them and modified the function to add this line at the start

if (kDebugMode) return;

I restarted the IDE, run the app with this code

print(kDebugMode); // Prints true

The print function shouldn’t have printed anything. If I go and check the implementation of those print function, my if condition line is still there.

So, what am I doing wrong?

>Solution :

You probably don’t want to modify the source code anyway.
Instead, you can use Zone to override the print behavior in your code without modifying the SDK.

You can do:

import 'dart:async';

void main() {
  runZoned(
    () => print('Hello world'),
    zoneSpecification: ZoneSpecification(
      print: (self, parent, zone, line) {
        // Your logic here:
        // if (kDebugMode) return;
        // Now use the original print implementation:
        parent.print(zone, 'This is a custom print: $line');
      },
    ),
  );
}

This example overrides print to customize the output. In this example, even though we called print('Hello world'), the output will be This is a custom print: Hello world

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading