如何修改Dart中的`print`函数?

huangapple go评论67阅读模式
英文:

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

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?

英文:

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

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?

答案1

得分: 4

以下是翻译好的内容:

你可能不想修改源代码。
相反,你可以使用 Zone 来覆盖代码中的 print 行为,而不修改 SDK。

你可以这样做:

import 'dart:async';

void main() {
  runZoned(
    () => print('Hello world'),
    zoneSpecification: ZoneSpecification(
      print: (self, parent, zone, line) {
        // 在这里添加你的逻辑:
        // if (kDebugMode) return;
        // 现在使用原始的 print 实现:
        parent.print(zone, '这是自定义的打印输出: $line');
      },
    ),
  );
}

这个示例覆盖了 print 以自定义输出。在这个示例中,尽管我们调用了 print('Hello world'),但输出将是 这是自定义的打印输出: Hello world

英文:

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

huangapple
  • 本文由 发表于 2023年4月13日 17:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定