【问题标题】:Flutter-web: Provider loss of state when browser refreshFlutter-web:浏览器刷新时提供者状态丢失
【发布时间】: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.dartsidebar.darthome_screen.dart

标签: flutter provider flutter-web


【解决方案1】:

您可以使用 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;
  }
}

【讨论】:

    猜你喜欢
    • 2010-10-07
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2021-06-28
    • 2012-03-26
    • 2019-03-24
    相关资源
    最近更新 更多