Flutter:从配置单元框创建对象流

nwnhqdif  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(384)

我正在尝试访问一些用户设置,这些设置会在整个应用程序中更改和访问。为此,我使用hive从一个框中检索用户设置。我想通过打开 UserSettings 从检索的对象 Hive.box('settings').get(userID) 流入一条小溪,然后注入 StreamProvider .
我该怎么转身呢 Hive.box('settings').get(userID) 变成一条小溪?
编辑:以下是我迄今为止的代码实现:
本地数据库.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); 
}

main.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()
    ),
  }
}
xmd2e60i

xmd2e60i1#

通过这个问题,我可以假设没有办法得到观察到的初始值,只需要 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),
      ),
    );
  },
)
nr9pn0ug

nr9pn0ug2#

使用 box.watch() 接下来是一个伪代码,只是一个例子

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

ps如果你将在执行卡住-联系我的意见帮助

相关问题