【发布时间】:2020-07-28 15:18:00
【问题描述】:
所以我想知道为什么提供者在浏览器刷新时会丢失状态。刷新/重新加载后不应该保持状态吗?
非常感谢您的帮助
flutter 的默认项目
home: ChangeNotifierProvider<Counter>(
create: (_) => Counter(),
child: MyHomePage(title: 'Flutter Demo Home Page')),
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({this.title});
@override
Widget build(BuildContext context) {
final counter = Provider.of<Counter>(context);
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many
times:',
),
Text(
'${counter.value}',
style:
Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counter.increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
这里是提供者类
import 'package:flutter/foundation.dart';
class Counter with ChangeNotifier {
int value=0;
void increment() {
value++;
notifyListeners();
}
}
【问题讨论】:
-
我确实相信刷新页面与重新打开应用程序是一回事,这意味着所有状态都会丢失
-
哎呀,有什么解决方法吗?为此,尤其是在网络中,当您需要在刷新后保持状态时
-
我不这么认为,除非您将数据保存在数据库中或本地共享首选项中
-
在 Flutter web 上使用 Riverpod,似乎浏览器刷新并没有像
void main那样走得太远,但会重建 UI,所以我要尝试的解决方案是将状态保存到共享首选项, 使用冻结的类使myClassInstantce.ToJson()更容易,然后在最可能的 UI 文件的InitState()中使用FromJson()重新加载,比如appbar.dart、sidebar.dart或home_screen.dart
标签: flutter provider flutter-web