Flutter GetIt插件-GetIt内部未注册任何类型的xxx [英] Flutter GetIt Plugin - No type xxx is registered inside GetIt
问题描述
我按照示例项目所示进行了所有设置:
I set everything up as shown in the example project:
import 'package:get_it/get_it.dart';
import 'package:places/services/authService.dart';
final locator = GetIt.instance;
void setupLocator() {
locator.registerSingleton<AuthService>(AuthService());
print("registered");
}
呼叫已保存在主文件中
void main() {
setupLocator();
runApp(MyApp());
}
我有一些检查,定位器在哪里也可以正确返回我的AuthService
I have some Check where the locator also correctly return my AuthService
class AuthGuardView extends StatefulWidget {
AuthGuardView({Key key}) : super(key: key);
@override
_AuthGuardViewState createState() => _AuthGuardViewState();
}
class _AuthGuardViewState extends State<AuthGuardView> {
@override
Widget build(BuildContext context) {
return ViewModelProvider<AuthGuardViewModel>.withConsumer(
viewModel: AuthGuardViewModel(),
onModelReady: (model) => model.initialise(),
builder: (context, model, child) => model.isLoggedIn
? Container(
color: Colors.white,
child: Text("Logged In"),
)
: SignUpView(),
);
}
}
class AuthGuardViewModel extends ChangeNotifier {
AuthService _authService = locator<AuthService>();
bool isLoggedIn = false;
void initialise() async {
isLoggedIn = await _authService.isLoggedIn();
notifyListeners();
}
}
如果在SignUpView的ViewModel中执行完全相同的操作,则会出现以下错误
If I do the exact same thing inside the ViewModel for the SignUpView I get the following error
flutter: The following assertion was thrown building SignUpView(dirty, state: _SignUpViewState#01129):
flutter: No type AuthService is registered inside GetIt.
flutter: Did you forget to pass an instance name?
flutter: (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;did you
flutter: forget to register it?)
flutter: 'package:get_it/get_it_impl.dart':
flutter: Failed assertion: line 248 pos 14: 'instanceFactory != null'
在AuthGuard的ViewModel中,我确实成功检索了auth服务.我也注释掉了定位器代码(因为我认为这可能是异步调用或类似的东西),但是相同的错误仍然存在.
In the ViewModel for the AuthGuard I do successfully retrieve the auth service. I also commented out the locator code (because I thought it might be the async call or something like that) but the same error persists.
我正在使用get_it:^ 4.0.1,但是降级到3.x.x时错误仍然存在
I am using get_it: ^4.0.1 but the error persists when downgrading to 3.x.x
这是SignUpViewModel
Here the SignUpViewModel
class SignUpViewModel extends ChangeNotifier {
SignUpViewModel(){
if(locator.isRegistered<AuthService>()) {
AuthService _authService = locator<AuthService>();
}
}
var textInputFormatter = [
WhitelistingTextInputFormatter(RegExp(r'\d')),
PhoneNumberTextInputFormatter()
];
var textEditingController;
var context;
}
推荐答案
使用 pubspec.yaml
中的最新 get_it
版本(现在是 get_it:^4.0.2
)为我解决此问题.您可以在这篇中等文章中查看更多信息.
Using the latest get_it
version in pubspec.yaml
( now it is get_it: ^4.0.2
) resolve the issue for me.
You can have a look at this medium article for more info.