3

我正在尝试访问一些在整个应用程序中更改和访问的用户设置。为此,我使用 Hive 从框中检索用户设置。我想通过将UserSettings检索Hive.box('settings').get(userID)到的对象转换为将被馈送到StreamProvider.

我将如何Hive.box('settings').get(userID)变成流?

编辑:到目前为止,这是我的代码实现:

local_database.dart

static Stream<UserSettings> get userSettings {
  return Hive.box('settings').watch(key: userID)?.map((boxEvent) {
    return boxEvent.value; // ========> value is always null from boxEvent
  });
}

static void saveUserSettings(UserSettings userPref) {
  Hive.box('settings').put(userID, userPref); 
}

主要.dart

class Launch extends StatefulWidget {
  @override
  _LaunchState createState() => _LaunchState();
}

class _LaunchState extends State<Launch> {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider<User>.value(value: AuthService.user),
        StreamProvider<UserSettings>.value(value: LocalDatabase.userSettings),
      ],
      child: MaterialApp(
        title: 'MyApp',
        home: AuthWrapper(),
      ),
    );
  }

设置.dart

class SettingsScreen extends StatefulWidget {
  @override
  _SettingsScreenState createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  UserSettings _settings;

  @override
  Widget build(BuildContext context) {
    _settings = Provider.of<UserSettings>(context);

    print(_settings.useLightTheme); // =====> Always returns null

    return Scaffold(
      appBar: AppBar(title: 'Settings'),
      body: Container()
    ),
  }
}
4

2 回答 2

3

利用box.watch()

接下来是一个伪代码,例如

Stream<User> listen() => box
      .watch(userID)
      .map(...) // somehow map your User
      .startWith(box.get(userID)); // initial value before any changes

PS如果您将坚持实施-请在评论中与我联系以寻求帮助

PS 2:该startWith方法是rxdart包提供的扩展,所以请记住这一点

于 2020-07-07T19:41:53.993 回答
3

通过这个问题,我可以假设没有办法在手表上获得初始值,这可能只是listenable

ValueListenableBuilder(
  valueListenable: Hive.box('settings').listenable(),
  builder: (context, box, widget) {
    return Center(
      child: Switch(
        value: box.get('darkMode', defaultValue: false),
        onChanged: (val) => box.put('darkMode', val),
      ),
    );
  },
)
于 2020-09-20T05:30:56.477 回答