当前位置: 首页 > 知识库问答 >
问题:

基于服务定位器的颤振依赖注入

何涵畅
2023-03-14

我正在尝试开发一个具有多个页面的Flutter应用程序。我有一个SignInService,我试图注入在不同的页面使用get_it服务定位器。

服务定位器。飞奔

final locator = GetIt.instance;
void setupLocator() {
  locator.registerSingleton<SignInService>(SignInService());
  locator.registerSingleton<LocationService>(LocationService());
}

ervice.dart

class SignInService {
  GoogleSignInAccount googleAccount;
  FirebaseUser firebaseUser;
  FirebaseAuth _auth = FirebaseAuth.instance;
.
.
}

当我登录时,firebaseUser变量正在该类中设置,并且该值不为null。

当我在像这样的另一个页面中使用它时,我得到一个空值。

E/flatter(20069):[ERROR:flatter/lib/ui/ui\u dart\u state.cc(157)]未处理的异常:NoSuchMethodError:对null调用了getter“uid”。E/flatter(20069):接收器:空E/flatter(20069):尝试呼叫:uid

另一页。飞奔

class _AnotherPageState extends State<AnotherPage> {
  final _signInService = locator<SignInService>();
  Firestore _firestore = Firestore.instance;

 _getUserCity() async {
    DocumentSnapshot snapshot = await _firestore
        .collection('users')
        .document(_signInService.firebaseUser.uid) //throws uid called on null error
        .get();
    _city = snapshot.data["city"];
  }


 _getPackage() async {
    _getUserCity();
    .
    .
}

@override
  initState(){
    super.initState();
    _getPackage();
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        //...
     );
  }

共有1个答案

卜高超
2023-03-14

它不是null,如果你做GetIt.find(YourName);作为第一行

 类似资料:
  • 因为Flatter\u math\u fork 获取:^4.6.1获取存储:2.0.3 dio:^4.0.4 dio\u http\u缓存:0.3.0 webview_flutter:^2.8.0flutter_html:^2.0.0url_launcher:^6.0.17 firebase\u消息:^11.2.4 cloud\u firestore:^3.1.5 firebase\u认证:^3.

  • 无法确定任务“:app:processDebugResources”的依赖项。 无法解决配置的所有任务依赖关系: app: dedegRuntimeClasspath。无法解决com.facebook.android: facebook登录:[5,6)。 所需:项目:应用程序 尝试:使用--stack跟踪选项运行以获取堆栈跟踪。使用--info或--debug选项运行以获取更多日志输出。运行--c

  • 在使用解决版本问题时,我得到以下错误: 因为google_map_location_picker 3.3.3依赖于intl>=0.16.0<=0.16.1,而sdk中的每个flutter_localizations版本都依赖于intl 0.17.0,所以google_map_location_picker 3.3.3与sdk中的flutter_localizations不兼容。因此,由于food_

  • 我想用di。在《颤栗》中,我加上这个https://pub.dartlang.org/packages/di打包我的项目,我开始读这篇文章https://webdev.dartlang.org/angular/guide/dependency-injection文章,但我不完全理解。 所以没关系:在服务类(例如:MyServices)上使用@Injectable()注释,但是如何注入其他类呢?例如

  • 当我开始模拟我的android手机和活动开发者模式以及USB调试时,我收到了这些消息,我尝试了一些方法,但没有成功。请在此处输入图像描述 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

  • 当我在android studio中运行我的第一个flutter应用程序时,我收到了这个错误。我的模拟器互联网连接和飞行模式是关闭的。我看到了其他类似的问题,但没有一个像这个错误,他们没有帮助我。有人能帮我吗? 如果需要更多细节,请告诉我。谢谢。