flutter - Riverpod,在 BuildContext 和 Provider 之外读取状态

标签 flutter dart riverpod

我正在努力弄清楚为什么这不起作用(而不是说明它应该起作用的文档)。
我有一个像这样的提供者

import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:putin_flutter_client/api/client.dart';
import 'package:putin_flutter_client/api/storage.dart';

final userProvider = StateNotifierProvider((_) => UserNotifier());

class UserNotifier extends StateNotifier<UserState> {
  UserNotifier() : super(UserState());

  set username(String username) {
    state = UserState(username: username, password: state.password, jwt: state.jwt);
    secureStorageWrite('username', username);
  }

  set password(String password) {
    state = UserState(username: state.username, password: password, jwt: state.jwt);
    secureStorageWrite('password', password);
  }

  set jwt(String jwt) {
    state = UserState(username: state.username, password: state.password, jwt: jwt);
    Client.jwt = jwt;
    secureStorageWrite('jwt', jwt);
  }

  String get jwt {
    return state.jwt;
  }

  Future<void> initState() async {
    final user = await UserState.load();
    state.username = user.username;
    state.password = user.password;
    state.jwt = user.jwt;
  }
}

class UserState {
  String username;
  String password;
  String jwt;

  UserState({
    this.username,
    this.password,
    this.jwt,
  });

  static Future<UserState> load() async {
    return UserState(
      username: await secureStorageRead('username'),
      password: await secureStorageRead('password'),
      jwt: await secureStorageRead('jwt'),
    );
  }
}
最终深入一些小部件,这样的事情会更新状态
// usilizing the setter on the provider to update the state...
user.jwt = data['token'];
现在在代码的其他部分我管理 http 客户端。这显然无法访问BuildContext等等,所以我执行以下操作以从存储的状态中检索 jwt 值。
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:putin_flutter_client/state/user.dart';

class Client extends http.BaseClient {
  final http.Client _client = http.Client();

  Future<http.StreamedResponse> send(http.BaseRequest request) {
    // Get the container as per riverpod documentation
    final container = ProviderContainer();
    // Access the value through the getter on the provider
    final jwt = container.read(userProvider).jwt;

    request.headers['user-agent'] = 'myclient::v1.0.0';
    request.headers['Content-Type'] = 'application/json';
    if (jwt != null) {
      request.headers['X-Auth-Token'] = jwt;
    }
    return _client.send(request);
  }
}
这始终为空,并且 UserState 几乎为空(所有成员都为空)。
riverpod documentation它说这应该有效
test('counter starts at 0', () {
  final container = ProviderContainer();

  StateController<int> counter = container.read(counterProvider);
  expect(counter.state, 0);
});
有人可以帮我弄清楚上面的例子有什么问题吗?

最佳答案

正如@moulte 指出的(真的很感谢)可以通过在外部实例化并通过 UncontrolledProviderScope 将其注入(inject)到小部件范围来访问提供者作为全局变量并且独立于上下文。 .重要的部分是记住在应用程序终止之前处理全局提供程序,否则它永远不会真正终止。
这是一个示例代码

/// file /state/container.dart
import 'package:hooks_riverpod/hooks_riverpod.dart';
final container = ProviderContainer();

/// file /main.dart
void main() async {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyApp createState() => _MyApp();
}

class _MyApp extends State<MyApp> {

  @override
  void dispose() {
    super.dispose();
    // disposing the globally self managed container.
    container.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return UncontrolledProviderScope(container: container,
      child: MaterialApp(
      // The usual widget tree
    );
  }
}

/// Somewhere in a file that is not aware of the BuildContext
/// here's how client.dart accesses the provider
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:putin_flutter_client/state/container.dart';
import 'package:putin_flutter_client/state/user.dart';


class Client extends http.BaseClient {
  final http.Client _client = http.Client();

  Future<http.StreamedResponse> send(http.BaseRequest request) {
    // Simply accessing the global container and calling the .read function
    var jwt = container.read(userProvider.state).jwt;
    request.headers['user-agent'] = 'putin_flutter::v1.0.0';
    request.headers['Content-Type'] = 'application/json';
    if (jwt != null) {
      request.headers['X-Auth-Token'] = jwt;
    }
    return _client.send(request);
  }
}

关于flutter - Riverpod,在 BuildContext 和 Provider 之外读取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66556027/

相关文章:

flutter - 在具有空安全性的 flutter 中将函数作为参数传递

dart - 如何使用 flutter 删除 Firestore 文档中的字段

flutter - flutter中的Riverpode和Hooks,如何实现异步调用的StateNotifier?

flutter - 当用户点击网页上的后退按钮时,Riverpod 会出现错误状态异常

带有动态列表的 Flutter 自定义滚动

string - 在 Dart 中分割表情符号字符串

angularjs - 服务器是否需要使用Polymer.dart和/或Angular.Dart运行某些CLIENT端DART应用程序?

flutter - List.add 和手动将项目添加到 Riverpod StateNotifier<List<String>> 之间的区别

Dart 代码在我的 Flutter 应用程序中表现不同。列表<动态 >' is not a subtype of type ' 列表< map <字符串,动态>>

flutter - 在Flutter中关闭应用程序时如何保存数据