2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】Dartにおける名前衝突の解決方法について

Last updated at Posted at 2020-05-13

概要

あまり多くはないかもしれませんが、同じ名前のクラスを二つ作り
それぞれを同じファイルで使用しようとした場合、名前解決が出来ずエラーが起きます。

具体的には以下の様な場合です。

sample_a.dart
class Foo {
  final int value;
  
  const Foo(this.value);
}

class Bar {
  final int value;

  const Bar(this.value);
}
sample_b.dart
class Foo {
  final String value;

  const Foo(this.value);
}
main.dart
import './sample_a.dart';
import './sample_b.dart';

void main() {
// ここでコンパイルエラー
//  Foo(1);
}

この様な場合に、両ファイルで定義されているのは Foo クラスです。
main.dartとしては、どちらのFooを使って良いかわかりません。

こんな時に名前解決をする手段は二つあります。

showキーワードを使う

実は、sample_a.dartをimportしたのはBarクラスが使いたかっただけ。
そんな時はこちらの解決策が有効です。

main.dart
import './sample_a.dart' show Bar;
import './sample_b.dart';

void main() {
  Foo("1"); // コンパイル出来る
}

この様にすると、mainにはBarしか読み込まれず、無事にFooが解決出来ます。

asキーワードを使う

両方のFooクラスを使いたい!
そんな時はこちらの解決策が有効です。

main.dart
import './sample_a.dart' as a;
import './sample_b.dart';

void main() {
  var a = a.Foo(1);
  var b = Foo("1");
}

この様に名前空間の様なものを定義する事が出来ます。
これで無事に名前解決が出来ます。

誰かのお役に立てば。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?