flutter 无法无条件调用方法“when”,因为接收方可以为“null”

rvpgvaaj  于 2023-04-22  发布在  Flutter
关注(0)|答案(3)|浏览(171)

我尝试使用Riverpod StateNotifierFutureProvider进行身份验证,但在使用when方法时遇到错误
无法无条件调用方法“when”,因为接收方可以是“null”。请尝试使调用有条件(使用“?.')或向目标('!')添加null检查。
即使在添加!时,也会显示以下内容
未为类型“Object”定义方法“when”。n请尝试将名称更正为现有方法的名称,或定义名为“when”的方法。

class MainPage extends ConsumerWidget {
  const MainPage({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
  final state = ref.watch(emailPasswordSignInControllerProvider);

  return state.when(
    data: (state) {
      return state == AuthState.authenticated
          ? const SharedLayout()
          : const LoginScreen();
    },
    error: (error, stackTrace) => const Scaffold(
      body: Center(child: Text("Error")),
    ),
    loading: () => const Scaffold(
      body: Center(
        child: CircularProgressIndicator(),
      ),
    ),
  );

这里是控制器:

class EmailPasswordSignInController extends StateNotifier<AsyncValue<AuthState>> {
  EmailPasswordSignInController({required this.authRepository})
      : super(const AsyncValue.data(AuthState.notAuthenticated));
  final AuthRepository authRepository;

  Future<void> submit(String email, String password) async {
    try {
      state = const AsyncValue.loading();
      await authRepository.signInWithEmailAndPassword(email, password);
      state = const AsyncValue.data(AuthState.authenticated);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }
}

final emailPasswordSignInControllerProvider = StateNotifierProvider((ref) {
  final authRepository = ref.watch(authRepositoryProvider);
  return EmailPasswordSignInController(authRepository: authRepository);
});

这是我的仓库:

class AuthRepository {
  Future<String> signInWithEmailAndPassword(
    String email, 
    String password,
  ) async {
    try {
      final String token;
      final Map<String, dynamic> jsonData;
      final url = Uri.parse('http://192.168.1.9:5000/api/v1/auth/login');
      final response = await http.post(url,
          body: jsonEncode({
            "email": email,
            "password": password,
          }),
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          });
      jsonData = jsonDecode(response.body);
      if (response.statusCode == 200) {
        token = jsonData['token'];
        return token;
      }
      return "error";
    } on Exception catch (e) {
      print(e.toString());
      return e.toString();
    }
  }
}

final authRepositoryProvider = Provider<AuthRepository>((ref) {
  return AuthRepository();
});
zvms9eto

zvms9eto1#

错误是说state在你用final state = ref.watch(emailPasswordSignInControllerProvider);定义的地方可能会返回一个null值。所以如果你确定它不会返回null,你可以在那里添加一个null检查运算符

final state = ref.watch(emailPasswordSignInControllerProvider)!;

或者你可以有条件地调用它,这样如果state返回空值,它就不会执行.when:

return state?.when

您还需要像这样定义提供程序的类型:

final emailPasswordSignInControllerProvider = StateNotifierProvider<EmailPasswordSignInController, AsyncValue<AuthState>>( (ref)
eagi6jfj

eagi6jfj2#

final state = ref.watch(emailPasswordSignInControllerProvider) ?? "";

尝试使用它将工作,或使用在

final state = ref.watch(emailPasswordSignInControllerProvider ?? "");
hm2xizp9

hm2xizp93#

这修复了错误:

StateNotifierProvider<EmailPasswordSignInController, AsyncValue>((ref) {
  final authRepository = ref.watch(authRepositoryProvider);
  return EmailPasswordSignInController(authRepository: authRepository);
});

相关问题