13
10

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 5 years have passed since last update.

Flutter (Dart) で Singleton が何故か複数作られて意図通りのSingletonな動作をしてくれなかった悲しみ

Posted at

症状

Dart で Singleton なクラスを作るときは以下のようにするといける、といろいろなところで解説されている。

Singleton.dart
class Singleton {
  static final Singleton _singleton = new Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

この Singleton 2つのdartファイルにて参照しようとすると、なぜかインスタンスが2つ作られてしまう現象になやまされた。 (それじゃぁ、Singletonじゃない!!)

原因

import の書き方が package:.... に統一されていなかったため、Singletonが違うものとして認識されていた。(謎挙動。。。)

例えば以下のような感じ。このように、importの形式が違うとDartは別物として扱っちゃうらしい。。(なんでだろう・・・?)

main.dart
import 'singleton.dart'
some.dart
import 'package:mypj/singleton.dart'

解決策

package:... な書き方に統一する。

おわり

この謎の挙動、原因が全然つかめなくてものすごいハマった(T_T)。数時間使っちゃったよ。。。悲しみ。。。。。

もし同じ様な問題に悩まされている人がいたら、この投稿が役に立つといいな。。。。数時間使う前に。。。

検索しまくって出てきた以下に助けられました。感謝です。

13
10
4

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
13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?