有没有一种方法在Flutter中打印控制台消息?

88

我正在调试一款应用程序,但需要实时了解某些值。我想知道是否有办法在控制台中打印消息,类似于使用Javascript的console.log。

感谢您的帮助。

12个回答

96

print() 很可能是您要查找的内容。这里提供了有关 Flutter 调试的更多信息。


1
在生产应用程序中,打印语句是否不好,还是可以将打印语句留给真实的应用程序? - Mattias
1
@Mattias,我个人不建议在生产应用中使用print/debug语句...(如果你有大量的print/debug语句,它将影响应用程序的性能,即使它只是微小的影响)。 - Rushikumar
有没有办法在调试器中编写 array [0]array[1] 或任何运行时分配的代码? - Jack
如果我想要在终端中打印而不是在 IDE 控制台中,我可以使用哪种方法? - Zhou Haibo
Flutter已经添加了一个名为avoid_print的linter,建议从生产代码中删除print语句。请查看'dart:developer'中的logdebugPrint - Dave Martorana

32

import 'dart:developer' 库中有更多有用的方法,其中之一是 log()

例如:

int i = 5;
log("Index number is: $i");

//output
[log] Index number is: 5

void log(String message, {DateTime time, int sequenceNumber, int level = 0, String name = '', Zone zone, Object error, StackTrace stackTrace})

Emit a log event.

This function was designed to map closely to the logging information collected by package:logging.

[message] is the log message
[time] (optional) is the timestamp
[sequenceNumber] (optional) is a monotonically increasing sequence number
[level] (optional) is the severity level (a value between 0 and 2000); see the package:logging Level class for an overview of the

possible values [name] (optional) is the name of the source of the log message [zone] (optional) the zone where the log was emitted [error] (optional) an error object associated with this log event [stackTrace] (optional) a stack trace associated with this log event

阅读更多:

print()来自 dart:core,并且它的实现为:

/// Prints a string representation of the object to the console.
void print(Object object) {
  String line = "$object";
  if (printToZone == null) {
    printToConsole(line);
  } else {
    printToZone(line);
  }
}

debugPrint()

/// Prints a message to the console, which you can access using the "flutter"
/// tool's "logs" command ("flutter logs").
///
/// If a wrapWidth is provided, each line of the message is word-wrapped to that
/// width. (Lines may be separated by newline characters, as in '\n'.)
///
/// By default, this function very crudely attempts to throttle the rate at
/// which messages are sent to avoid data loss on Android. This means that
/// interleaving calls to this function (directly or indirectly via, e.g.,
/// [debugDumpRenderTree] or [debugDumpApp]) and to the Dart [print] method can
/// result in out-of-order messages in the logs

// read more here: https://api.flutter.dev/flutter/foundation/debugPrint.html
DebugPrintCallback debugPrint = debugPrintThrottled;


/// Alternative implementation of [debugPrint] that does not throttle.
/// Used by tests. 
debugPrintSynchronously(String message, { int wrapWidth })

/// Implementation of [debugPrint] that throttles messages. This avoids dropping
/// messages on platforms that rate-limit their logging (for example, Android).
void debugPrintThrottled(String message, { int wrapWidth })

阅读更多

请注意,只有print()可接受任何类型并打印到控制台。 debugPrint()log()仅接受String。因此,您必须添加.toString()或使用字符串插值,就像我在提供的示例片段中所演示的那样。


1
log()是这些函数中唯一能够显示JSON完整结果的,谢谢。 - Inmer

27

您可以使用

print() 

函数或

debugPrint()

debugPrint()函数可以打印大量的输出。


1
需要在我的代码中添加 import 'package:flutter/material.dart'; - colin

10
我倾向于做类似的事情。
Foo foo;
try{
    foo = _someMethod(); //some method that returns a new object
} catch (e) {
    print('_someMethod: Foo Error ${foo.id} Error:{e.toString()}'); /*my custom error print message. You don't need brackets if you are printing a string variable.*/
}

8

使用调试打印避免在生产应用中记录日志。

debugPrint("Message");

你也可以在main.dart或其他文件中禁用或更改调试打印的实现,如下所示:
debugPrint = (String message, {int wrapWidth}) 
{
    debugPrintThrottled(message);//Or another other custom code
};

6
printdebugPrint 和其他一些方法都有字数限制,如果你需要在控制台打印较长的内容,可以采用以下方法:

创建这个方法:

void printWrapped(String text) {
  final pattern = RegExp('.{1,800}'); // 800 is the size of each chunk
  pattern.allMatches(text).forEach((match) => print(match.group(0)));
}

使用方法:

printWrapped("Your very long string ...");

Source


5
debugPrint()

最好使用debugPrint()而不是print(),因为它试图减少在Android内核上日志行丢失或顺序混乱的情况。
参考:Flutter中的日志记录

4

关于使用字符串连接的另一个答案:

// Declaration
int number = 10;


//Button Action
RaisedButton(
child: Text("Subtract Me"),
onPressed: () {
      number = number - 1;
      print('You have got $number as result');
      print('Before Value is ${number - 1} and After value is ${number + 1}');
    },
),

//Output:
flutter: You have got 9 as result
flutter: Before Value is 8 and After value is 10

2
我使用类似这样的东西。print()函数可以打印一定量的数据。因此,我使用这个日志记录。
    import 'dart:developer';
    
    debugLog({String tag = '', required dynamic value}) {
      log("TAG $tag : ${value.toString()}");
    }

1

我认为这可能会对你有所帮助,因为我也曾陷入许多无法知道dart文件输出的方式,因此我通过按照视频中显示的步骤得到了解决方案。

https://www.youtube.com/watch?v=hhP1tE-IHos

这里展示了遵循视频后它是如何工作的一个示例。 检查左侧列,其中显示了profile变量所包含的值,即null Dart dev tools working


2
虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅有链接的答案可能会失效。- 来自审查 - STA
好的,谢谢您的反馈,我会修改我的回复。我会尽力提供一些有帮助的建议。 - Spsnamta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接