我按照示例项目的设置进行了所有操作:
在主文件中调用
如果我在SignUpView的ViewModel中做完全相同的事情,会出现以下错误。
在AuthGuard的ViewModel中,我成功地检索了auth服务。我还注释掉了locator代码(因为我认为它可能是异步调用或类似的东西),但是相同的错误仍然存在。
我正在使用get_it: ^4.0.1,但是当降级到3.x.x时,错误仍然存在。
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。
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中做完全相同的事情,会出现以下错误。
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服务。我还注释掉了locator代码(因为我认为它可能是异步调用或类似的东西),但是相同的错误仍然存在。
我正在使用get_it: ^4.0.1,但是当降级到3.x.x时,错误仍然存在。
这里是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;
}