0

I wonder, if a dart or flutter method exists, which returns complete type information about the structure of a variable's value as a string.

E.g., if some print( someValue.toString() ); emits this

  {"user":"userName","state":"valid"}

I don't know if it is a Map or a String.

But how do I get a string, which describes a variable's value / structure?

Something, that's like PHP's print_r(), which print stuff like this:

Array
(
    [a] => Apfel
    [b] => Banane
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
SteAp
  • 11,853
  • 10
  • 53
  • 88

3 Answers3

1

There is nothing like print_r() available natively in Dart.
However, it would be possible to use the following functionalities to build e.g. a function like print_r() from PHP.

You can evaluate the type of someValue using runtimeType.

String someValueType = someValue.runtimeType.toString();
String someValueString = someValue.toString();

If you want to compare, you can also use is. More on that here.
Dart is a strongly typed language, which means that you could also enforce types (List a; String b), which makes a function like print_r() redundant for Dart.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
1

If it is about server-side code you can use reflection to create a function that produces such an output for every value.

If it is about your own classes, you can implement toString() to make the objects render themselves this way when they are printed

class Person {
  Foo(this.firstName, this.lastName);

  String firstName;
  String lastName;

  @override
  String toString() => '''
firstName: $firstName
lastName: $lastName
''';      
}

print(new Person('John', 'Doe'));
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Best way to do is

print(”$someValue“);

It will return a structured string which similar to JSON.

Poohspear
  • 29
  • 3