'How can I call a function from a method of the same name?
I want to have a print method in my class, also I want to be able to use print inside it
example:
class A {
String val;
void print() {
print(val);
}
}
using print will refer to the method of class A, how can I specify the full path of the method I want to call?
Solution 1:[1]
A couple of different ways to resolve the name conflict:
As Christopher Moore mentioned, you can explicitly import
dart:corewith a prefix. Note that if you don't want to prefix everything fromdart:core, you could import it twice, once into the global namespace and again into the prefixed namespace:import 'dart:core'; import 'dart:core' as core;Then you would be able to explicitly use
core.printwithin yourprintmethod and useprintnormally everywhere else.Note that if you have a method trying to call a global function with the same name within the same Dart library, you could split your code into multiple files, or your library could import itself with a prefix:
foo.dart:import 'foo.dart' as foo; class SomeClass { void f() => foo.f(); } void f() { // Do stuff. }You alternatively could explicitly create another reference to the normal
printfunction with a different name:final _print = print; class A { String val; void print() { _print(val); } }
Solution 2:[2]
I'm assuming that you're trying to call the print function of dart:core.
You can explicitly import dart:core and specify a prefix for it with the as keyword:
import 'dart:core' as core;
class A {
core.String val;
void print() {
core.print(val);
}
}
Likely the biggest issue with this is now you have to have to prefix everything that's in dart:core like the String in your example.
Solution 3:[3]
import "dart:core";
import "dart:core" as core show print;
class Class {
static print(_string) {
if (kDebugMode) {
core.print(_string);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Christopher Moore |
| Solution 3 | Greenlight |
