95

I'm debugging an app, but I need to know some values in the fly, I was wondering if there's a way to print a message in console like console.log using Javascript.

I appreciate the help.

0

12 Answers 12

102

print() is probably what you are looking for. Here's some more info on debugging in flutter.

5
  • 1
    is print bad to have in production app aswell or is it fine to leave the prints for real app?
    – Mattias
    Commented Mar 22, 2019 at 14:41
  • 1
    @Mattias I personally would not recommend having print/debug statements in a production app... (if you have rampant print/debug statements, it will affect the performance of the app --- even if it is a minuscule impact).
    – Rushikumar
    Commented Aug 17, 2019 at 18:41
  • Is there any way where we can write array [0], array[1] or any run time assignment in the debugger ?
    – Jack
    Commented Sep 27, 2019 at 10:18
  • If I want to print things in terminal instead of IDE console. Which method I could use?
    – Zhou Haibo
    Commented Nov 18, 2020 at 15:49
  • 1
    Flutter has added a the linter avoid_print suggesting the removal of print statements from production code. Check out log in 'dart:developer' or debugPrint Commented Jul 8, 2021 at 16:50
38

There are more helpful methods in import 'dart:developer' library and one of them is log().

example:

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

Read more.:

print() is from dart:core and its implementation:

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

Note that only the print() is taking any type and print to the console. debugPrint() and log() only take String. So, you have to add .toString() or use string interpolation like I shown in provided example snippet.

1
  • 1
    log() is the only one of those that shows me the whole result of a JSON, thanks.
    – Inmer
    Commented Sep 22, 2020 at 14:43
29

You can use

print() 

function or

debugPrint()

The debugPrint() function can print large outputs.

1
  • 1
    Requires import 'package:flutter/material.dart'; for me.
    – colin
    Commented Dec 12, 2019 at 10:24
10

I tend to do something similar to this

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

Use debug print to avoid logging in production application.

debugPrint("Message");

You can also disable or change debug print implementation in main.dart or any other file like this:

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

print, debugPrint and others have got some word limit restrictions, if you have something long to print on console, you can:

Create this method:

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

Usage:

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

Source

5
debugPrint()

Might as well use rather than print() as it attempts to reduce log line drop or being out of order on Android kernel

Refs:

Logging in Flutter

4

One more answer for 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
0
2

I use something like this. The print() function can print data up to some limit. So I use this log.

    import 'dart:developer';
    
    debugLog({String tag = '', required dynamic value}) {
      log("TAG $tag : ${value.toString()}");
    }
1

I think this might help you, because, I was also got stuck in many ways of knowing the output of my code in the dart file, hence I got the solution by following the steps, shown in the video.

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

here I have shown an instance of how it works after following the video. check the left side column where it shows about the value which profile variable carry i.e., null Dart dev tools working

2
  • 2
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – STA
    Commented Jan 13, 2021 at 10:03
  • ok, thanks for the feedback I will edit my response. and I will try to give some helpful suggestion
    – Spsnamta
    Commented Jan 13, 2021 at 10:33
0

you can simply use print('whatever you want to print') same as console.log() in javascript.

for more info you can check here.

0

Note that the print() and log() options both add their own labels at the start of the line, and apply additional formatting that can cause long lines to be truncated. In the case of a dart:io app, you can bypass this interception and mangling entirely by going directly to stdout/stderr, etc. as in stdout.write(), stdout.writeln(), etc. Likewise if you are looking to log explicitly to one or the other. I ran into this issue when adding CLI args to a flutter application.

Not the answer you're looking for? Browse other questions tagged or ask your own question.