gpt4 book ai didi

Flutter-web:浏览器刷新时提供程序丢失状态

转载 作者:行者123 更新时间:2023-12-04 11:36:21 28 4
gpt4 key购买 nike

所以我想知道为什么提供者在浏览器刷新时会丢失状态。刷新/重新加载后不应该保持状态吗?

Would Really appreciate the Help

default project for 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),
),
);
}
}

Here's the Provider Class

import 'package:flutter/foundation.dart';

class Counter with ChangeNotifier {

int value=0;
void increment() {

value++;
notifyListeners();
}
}

最佳答案

您可以使用 cookie 或跟踪状态和其他信息。我找到了这段代码,即使在刷新时也能工作。

import 'package:universal_html/html.dart' as html;

class CookieManager {

static addToCookie(String key, String value) {
// 2592000 sec = 30 days.
html.document.cookie = "$key=$value; max-age=2592000; path=/;";
}

static String getCookie(String key) {

String cookies = html.document.cookie;
List<String> listValues = cookies.isNotEmpty ? cookies.split(";") : List();
String matchVal = "";
for (int i = 0; i < listValues.length; i++) {
List<String> map = listValues[i].split("=");
String _key = map[0].trim();
String _val = map[1].trim();
if (key == _key) {
matchVal = _val;
break;
}
}
return matchVal;
}
}

关于Flutter-web:浏览器刷新时提供程序丢失状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61232367/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com