0

I am implementing setting switch where the value is directly loaded from the shared preference, and when it is changed the value is written into it, and trigger a rebuild to load it again. The setting switch is a HookWidget as follow:

import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

class SettingSwitch extends HookWidget {
  const SettingSwitch({required this.sharedPrefKey, required this.initial});

  final String sharedPrefKey;
  final bool initial;

  @override
  Widget build(BuildContext context) {
    final changeNotifier = useListenable(ChangeNotifier());
    return CupertinoSwitch(
      value: SharedPrefs.instance.getBool(sharedPrefKey) ?? initial,
      onChanged: (value) {
        SharedPrefs.instance.setBool(sharedPrefKey, value);
        changeNotifier.notifyListeners();
      }
    );
  }
}

where SharedPrefs is a class to cache the SharedPreferences instance with the init() method called at app startup:

import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefs {
  static late final SharedPreferences instance;

  static Future<SharedPreferences> init() async =>
      instance = await SharedPreferences.getInstance();
}

I am not sure if this is the optimal way to write the widget as I have never seen any code examples with a direct use of a bare ChangeNotifier without using it as a mixin or as a base class. Is this the best way to make a HookWidget which triggers a rebuild on its own?

Michael Tsang
  • 678
  • 5
  • 16
  • This seems like a pretty backwards way of doing this. I would either use a Stateful class, because this is a simple bool. Or I might opt for a useState, the changing of which will rebuild the widget just like this roundabout listener. – Randal Schwartz May 24 '23 at 23:11

0 Answers0