英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论