【发布时间】:2019-07-03 16:31:36
【问题描述】:
我在 SharedPreferences 中保留了多个帐户,并希望使当前帐户(用户在对话框中选择)可在整个应用程序中访问。当用户更改当前帐户时,UI 应自动更新以显示该帐户。但是,我尝试过的应用状态系统不会在当前用户更改时更新我的 StatefulWidgets。
我尝试过 SharedPreferences、InheritedWidget、Provider 和 ChangeNotifier。我一直无法监听 SharedPreferences 的变化,并且其他解决方案在状态变化时不会更新 UI。
// 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);
}
【问题讨论】:
-
如果需要,有多种方法可以强制重新绘制整个应用程序:stackoverflow.com/questions/43778488/…。
-
当学生改变时,学生的顶级提供者不会导致整个子树的完全重建吗? pub.dev/packages/provider
-
感谢您的回复!用户在对话框中选择一个新学生,更新提供者中的当前学生索引。我认为小部件树应该重建,但我在 _TodayState 初始化程序中的断点没有激活。
-
可能是在对话框而不是常规小部件中更新提供程序值?