【问题标题】:Is there a way to print a console message with Flutter?有没有办法用 Flutter 打印控制台消息?
【发布时间】:2019-01-16 23:26:33
【问题描述】:

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

感谢您的帮助。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    print() 可能是您正在寻找的。 Here's 更多关于 Flutter 调试的信息。

    【讨论】:

    • 在生产应用程序中打印不好还是可以将打印件留给真正的应用程序?
    • @Mattias 我个人不建议在生产应用程序中使用打印/调试语句...(如果您有猖獗的打印/调试语句,它会影响应用程序的性能 --- 即使影响很小)。
    • 有什么方法可以在调试器中编写array [0]array[1] 或任何运行时分配?
    • 如果我想在终端而不是 IDE 控制台中打印东西。我可以使用哪种方法?
    • Flutter 添加了一个 linter avoid_print 建议从生产代码中删除打印语句。在'dart:developer'debugPrint 中查看log
    【解决方案2】:

    我倾向于做类似的事情

    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.*/
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用

      print() 
      

      函数或

      debugPrint()
      

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

      【讨论】:

      • 我需要import 'package:flutter/material.dart';
      【解决方案4】:

      Concatenate with String 的另一个答案:

      // 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
      

      【讨论】:

        【解决方案5】:

        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})

        发出日志事件。

        此功能旨在紧密映射到日志信息 按 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
        

        可能的值 [name](可选)是日志消息来源的名称 [zone](可选)发出日志的区域 [error](可选)与此日志事件关联的错误对象 [stackTrace](可选)与此日志事件关联的堆栈跟踪

        Read more.:

        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 })
        

        Read more.

        请注意,只有print() 采用任何类型并打印到控制台。 debugPrint()log() 只接受String。因此,您必须添加 .toString() 或使用字符串插值,如我在提供的示例 sn-p 中所示。

        【讨论】:

        • log() 是唯一一个向我展示 JSON 的全部结果的方法,谢谢。
        【解决方案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

        【讨论】:

          【解决方案7】:

          使用调试打印来避免登录生产应用程序。

          debugPrint("Message");
          

          您还可以在 main.dart 或任何其他文件中禁用或更改调试打印实现,如下所示:

          debugPrint = (String message, {int wrapWidth}) 
          {
              debugPrintThrottled(message);//Or another other custom code
          };
          

          【讨论】:

            【解决方案8】:

            您可以在 javascript 中简单地使用 print('whatever you want to print')console.log() 相同。

            更多信息,您可以check here

            【讨论】:

              【解决方案9】:

              我认为这可能对您有所帮助,因为我也被困在许多方面,无法了解我的代码在 dart 文件中的输出,因此我按照视频中显示的步骤得到了解决方案。

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

              这里我展示了一个实例,说明它在观看视频后是如何工作的。 检查左侧列,其中显示了 profile 变量携带的值,即 null

              【讨论】:

              • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
              • 好的,感谢您的反馈,我将编辑我的回复。我会尽力提供一些有用的建议
              【解决方案10】:
              debugPrint()
              

              最好使用而不是print(),因为它试图减少日志行丢失或在 Android 内核上出现故障

              参考:

              Logging in Flutter

              【讨论】:

                猜你喜欢
                • 2017-03-18
                • 2021-10-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-03-07
                • 2010-11-25
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多