Flutter Riverpod:如何实施FutureProvider?

时间:2020-07-22 02:48:47

标签: flutter

我使用Flutter Riverpod包来处理http请求。我有一个简单的Http get 请求以显示服务器中的所有用户,并且我使用Flutter Riverpod软件包中的 FutureProvider 对其进行管理。

API

class UserGoogleApi {
  Future<List<UserGoogleModel>> getAllUser() async {
    final result = await reusableRequestServer.requestServer(() async {
      final response =
          await http.get('${appConfig.baseApiUrl}/${appConfig.userGoogleController}/getAllUser');
      final Map<String, dynamic> responseJson = json.decode(response.body);
      if (responseJson['status'] == 'ok') {
        final List list = responseJson['data'];
        final listUser = list.map((e) => UserGoogleModel.fromJson(e)).toList();
        return listUser;
      } else {
        throw responseJson['message'];
      }
    });
    return result;
  }
}

用户提供商

class UserProvider extends StateNotifier<UserGoogleModel> {
  UserProvider([UserGoogleModel state]) : super(UserGoogleModel());
   
Future<UserGoogleModel> searchUserByIdOrEmail({
    String idUser,
    String emailuser,
    String idOrEmail = 'email_user',
  }) async {
    final result = await _userGoogleApi.getUserByIdOrEmail(
      idUser: idUser,
      emailUser: emailuser,
      idOrEmail: idOrEmail,
    );
    UserGoogleModel temp;
    for (var item in result) {
      temp = item;
    }
    state = UserGoogleModel(
      idUser: temp.idUser,
      createdDate: temp.createdDate,
      emailUser: temp.emailUser,
      imageUser: temp.emailUser,
      nameUser: temp.nameUser,
      tokenFcm: temp.tokenFcm,
      listUser: state.listUser,
    );

    return temp;
  }

  Future<List<UserGoogleModel>> showAllUser() async {
    final result = await _userGoogleApi.getAllUser();
    state.listUser = result;
    return result;
  }
}

final userProvider = StateNotifierProvider((ref) => UserProvider());

final showAllUser = FutureProvider.autoDispose((ref) async {
  final usrProvider = ref.read(userProvider);
  final result = await usrProvider.showAllUser();
  return result;
});

设置完成后,我可以像这样直接调用 showAllUser

    Consumer((ctx, read) {
              final provider = read(showAllUser);
              return provider.when(
                data: (value) {
                  return ListView.builder(
                    itemCount: value.length,
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      final result = value[index];
                      return Text(result.nameUser);
                    },
                  );
                },
                loading: () => const CircularProgressIndicator(),
                error: (error, stackTrace) => Text('Error $error'),
              );
            }),

如果http请求没有必需的参数,这没问题,但是如果我的http请求具有必需的参数,我就遇到了问题。我不知道该如何处理。

比方说,我还有另一个http 获取来显示来自id用户或电子邮件用户的特定用户。然后API如下:

API

  Future<List<UserGoogleModel>> getUserByIdOrEmail({
    @required String idUser,
    @required String emailUser,
    @required String idOrEmail,
  }) async {
    final result = await reusableRequestServer.requestServer(() async {
      final baseUrl =
          '${appConfig.baseApiUrl}/${appConfig.userGoogleController}/getUserByIdOrEmail';
      final chooseURL = idOrEmail == 'id_user'
          ? '$baseUrl?id_or_email=$idOrEmail&id_user=$idUser'
          : '$baseUrl?id_or_email=$idOrEmail&email_user=$emailUser';
      final response = await http.get(chooseURL);
      final Map<String, dynamic> responseJson = json.decode(response.body);
      if (responseJson['status'] == 'ok') {
        final List list = responseJson['data'];
        final listUser = list.map((e) => UserGoogleModel.fromJson(e)).toList();
        return listUser;
      } else {
        throw responseJson['message'];
      }
    });
    return result;
  }

用户提供商

final showSpecificUser = FutureProvider.autoDispose((ref) async {
  final usrProvider = ref.read(userProvider);

  final result = await usrProvider.searchUserByIdOrEmail(
    idOrEmail: 'id_user',
    idUser: usrProvider.state.idUser, //  => warning on "state"
  );
  return result;
});

当我使用usrProvider.state.idUser从userProvider访问idUser时,收到此警告。 The member 'state' can only be used within instance members of subclasses of 'package:state_notifier/state_notifier.dart'.

我在this上提出的问题与之类似,但是对于这个问题,我已经知道可以使用read(userProvider.state)来解决,但是在 FutureProvider 中,我无法使用{{1 }}。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

警告:这不是长期解决方案

假定在每次使用后您的FutureProvider都得到适当处置,这是一个适当的解决方法,直到对Riverpod进行新更改为止。我进行了快速测试,发现它确实有效。确保您定义了这样的吸气剂,并且不要覆盖StateNotifier定义的默认值。

class A extends StateNotifier<B> {
...
  static final provider = StateNotifierProvider((ref) => A());

  getState() => state;
...
}
final provider = FutureProvider.autoDispose((ref) async {
    final a = ref.read(A.provider);
    final t = a.getState();
    print(t);
});

不理想,但似乎是一个很好的解决方法。我相信状态在外部不可访问的意图是确保状态操纵由StateNotifier本身处理,因此在此期间使用吸气剂将不会是世界末日。