I have several accounts persisted in SharedPreferences and want to make the current account (which the user choses in a dialog) accessible across the entire app. When the user changes the current account, the UI should automatically update to show that account. However, the app state systems I have tried do not update my StatefulWidgets when the current user changes.
I have tried SharedPreferences, InheritedWidget, Provider, and ChangeNotifier. I haven't been able to listen to SharedPreferences changes, and the other solutions don't update the UI when the state changes.
// Main.dart
void main() => runApp(
ChangeNotifierProvider<AppStateManager>.value(
value: AppStateManager(),
child: MyApp()
)
);
class AppStateManager extends ChangeNotifier {
int _currentStudentIndex;
int get currentStudentIndex => _currentStudentIndex;
set currentStudentIndex(int index) {
_currentStudentIndex = index;
notifyListeners();
}
}
// Code that runs when the user selects a new account
onPressed: () {
Provider.of<AppStateManager>(context).currentStudentIndex = index;
Navigator.pop(context);
},
// The state for my StatefulWidget
_TodayState() {
getCurrentStudent().then((student) => setState(() {
_currentStudent = student;
}));
}
Future<Student> getCurrentStudent() async {
List<String> students = await PreferencesManager.getStudents();
final AppStateManager stateManager = Provider.of<AppStateManager>(context);
Map<String, dynamic> currentStudent = jsonDecode(students[stateManager.currentStudentIndex ?? 0]);
return Student.fromJson(currentStudent);
}