How to save to web local storage in flutter web

后端 未结 6 1993
渐次进展
渐次进展 2020-12-30 01:02

I have a web site built with flutter for web and currently, am trying to save to web local storage or cookie but can\'t seem to find any plugin or way to ar

6条回答
  •  执念已碎
    2020-12-30 01:32

    i am using shared_preferences package to store data on location storage

    class SessionManager {
      static SessionManager manager;
      static SharedPreferences _prefs;
    
      static Future getInstance() async {
        if (manager == null || _prefs == null) {
          manager = SessionManager();
          _prefs = await SharedPreferences.getInstance();
        }
        return manager;
      }
    
      void putCityId(String cityId) {
        _prefs.setString("KEY_CITY_ID", cityId);
      }
    
      String getCityId() {
        return _prefs.getString("KEY_CITY_ID") ?? "";
      }
    }
    

    shared_preferences store data for current session only.

    If you want to store data permenently then you should use cookie to store data.

    Cookie used to store data on browsers cookie.

       import 'dart:html';
    
       class CookieManager {
          static CookieManager _manager;
    
          static getInstance() {
            if (_manager == null) {
              _manager = CookieManager();
            }
            return _manager;
          }
    
          void _addToCookie(String key, String value) {
            // 2592000 sec = 30 days.
            document.cookie = "$key=$value; max-age=2592000; path=/;";
          }
    
          String _getCookie(String key) {
            String cookies = document.cookie;
            List listValues = cookies.isNotEmpty ? cookies.split(";") : List();
            String matchVal = "";
            for (int i = 0; i < listValues.length; i++) {
              List map = listValues[i].split("=");
              String _key = map[0].trim();
              String _val = map[1].trim();
              if (key == _key) {
                matchVal = _val;
                break;
              }
            }
            return matchVal;
          }
        }
    

提交回复
热议问题