问题是当我将变量(String)作为参数提供给它保持不变的函数时。就像只有价值传递一样。
void main() {
String quote = "search";
print(quote);
f(quote);
print(quote);
}
void f(String txt) {
txt = "find";
}
结果是:
search
search
我想要的是:
search
find
Dart使用参数传递值,所以你希望看到它。
您可以将基元包装在类中,并在该类上实现变异函数。这样,您可以在逻辑上将可以修改数据的函数与数据分组。
main()
Quote quote = Quote('search');
print(quote.quote);
quote.f();
print(quote.quote);
}
class Quote {
String quote;
Quote(this.quote);
void f() {
quote = 'find';
}
}
或者您可以在不创建新类的情况下使用List
void main() {
List quote = ["search"];
print(quote[0]);
f(quote);
print(quote[0]);
}
void f(List txt) {
txt[0] = "find";
}