web-dev-qa-db-ja.com

Flutterの「xxxxxのオブジェクトのオブジェクトは登録されていません」という問題を修正する方法は?

使用するシングルトンオブジェクトを作成するためにget_itを使用しようとしています。 FireBaseに接続しているAPIの複数のオブジェクトを使用したくありません。シングルトンオブジェクトはFirebaseのAPI呼び出しのものです。

次のコードを使用しました

locator.registerLazySingleton<Api>(() => new Api('teams')) ;
 _

次のコードの仕組みになりますが

locator.registerLazySingleton<TeamViewModel>(() => new TeamViewModel()) ;
 _

APIクラスの構造は次のとおりです。

class Api{
  final Firestore _db = Firestore.instance;
  final String path;
  CollectionReference ref;
  
  Api( this.path ) {
    ref = _db.collection(path);
  }

  Future<QuerySnapshot> getDataCollection() {
     return ref.getDocuments() ;
  }
}`
 _

これが私がAPI Singletonオブジェクトを使用する方法です。

Api _api = locator<Api>();
 _

次のコードは元気ですが:

Api _api = Api('team');
 _

コンソールに次のエラーが発生します。

I/Flutter(2313):次の_ exceptionがマルチローヴィダーの建物を投げ込まれました。

I/Flutter(2313):例外:APIのオブジェクトはGetIt内に登録されていません

これがgetitを使用することができるかどうかを知りたいのですが、これはこれについて行く正しい方法ではありません。

7
Arpit Bansal

2021年にこのエラーに直面している人のための依存関係get_it:^ 5.0.3

クラスロケータを作ります。ダーツ

import 'package:get_it/get_it.Dart';
import 'package:rest_api_work/Service/note_service.Dart';

final locator = GetIt.instance;

void setUpLocator() 
{

locator.registerLazySingleton<NoteService>(() =>NoteService());

}
 _

これでこのメソッドを呼び出してくださいsetuplocator main.dartでは

  void main() 
 {

   setUpLocator() ;
   runApp(MyApp());
  }
 _

そして、データを表示するロケータクラスのプロパティを作成してください。

List<NoteForListing> notes = [];
 void initState()  {
         List<NoteForListing> service =  locator.get<NoteService>().getNotesList();
 
    setState(() {
      notes = service;    });
  
       super.initState();   }
 _

そして最後のnoteserverice.dart.

import 'package:rest_api_work/models/note_for_listing.Dart';

class NoteService
{
  List<NoteForListing> getNotesList()
  {
     return
     [
    new NoteForListing(
      noteID :"1",
      noteTitle:"Note 1",
      createDateTime:DateTime.now(),
      latestEditDateTime:DateTime.now()
    ),
       new NoteForListing(
      noteID :"2",
      noteTitle:"Note 2",
      createDateTime:DateTime.now(),
      latestEditDateTime:DateTime.now()
    ),
       new NoteForListing(
      noteID :"3",
      noteTitle:"Note 3",
      createDateTime:DateTime.now(),
      latestEditDateTime:DateTime.now()
    )
  ];
  
  }
}
 _
0
benten