【发布时间】:2021-02-16 16:20:15
【问题描述】:
我已经设法使用共享首选项来保存我的数据。加载应用程序后(关闭后), 数据在后台正确加载,但 UI 在启动时没有更新。
在用户点击日期之前,系统会一直显示默认 UI。 除此之外,给定重量的日期的刻度线也不显示。
我不知道该怎么办。 这是问题所在的演示:
UI not updating in accordance with the stored data (shared preferences)
class UserWeight {
int id;
final String weight;
double totalWeight = 0.0;
final String date;
String jsonString;
var listOfWeights = [];
UserWeight({this.weight, this.date});
void addWeight(String dt, String wt) {}
void removeWeight(String dt) {}
}
String getWeight(String dt) {
if (listOfWeights != null) {
for (var v in listOfWeights) {
if (v.containsKey('date')) {
if (v['date'] == dt) {
return double.parse(v['weight']).toString();
}
}
}
}
return kNoWeightText; // If there is no weight for given date
}
String serialize() {
jsonString = jsonEncode(listOfWeights);
return jsonString;
}
read() async {
final prefs = await SharedPreferences.getInstance();
// var b = List<Map<String, dynamic>>.from(jsonDecode(jsonString));
List<dynamic> s = jsonDecode(prefs.getString('listOfWeights') ?? []);
listOfWeights = s;
print("====START OF DECODE===");
print(listOfWeights);
for (var v in listOfWeights) {
print(v);
}
print("====END OF DECODE===");
}
saveData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('listOfWeights', serialize());
}
}
HomePage() 是在 main.dart 之后加载的第一个东西
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
// Other variables;
UserWeight uw = new UserWeight();
@override
void initState() {
uw.read();
}
void dispose() {}
.....
// this is called by builder:CalendarBuilders() of the TableCalendar() widget.
Widget _buildEventsMarker(DateTime date, List events) {
// this creates the tick marks... or it is supposed to do so.
// events parameter is not used
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
width: 25.0,
height: 25.0,
child: Center(
child: Icon(
uw.getWeight(date.toString()) != kNoWeightText ? Icons.check : null,
color: Colors.green,
),
),
);
}
}
请提出任何方法,或者如果需要提供程序包,则说明在此代码中将在哪些地方使用它。
谢谢。
【问题讨论】:
-
你在哪里调用 read() 方法??
-
在 initState(){}
-
在那之后你是在做 setState() 吗?
-
没有。它会在构建错误期间调用 setState()。
标签: flutter dart sharedpreferences