read method

  1. @override
Future<String> read()
override

Implementation

@override
Future<String> read() async {
  if (pathOrUrl.startsWith("http")) {
    var prefs = await SharedPreferences.getInstance();
    Map<String, String> headers = {
      'If-Modified-Since': prefs.getString('${pathOrUrl}_Last-Modified') ?? ''
    };
    var jwt = prefs.getString("idtoken") ?? prefs.getString("jwt") ?? '';
    var sid = prefs.getString("sid") ?? '';
    var q = sid.isEmpty ? '' : '?sid=$sid';
    headers.addAll({'Authorization': 'Bearer $jwt'});
    var body = prefs.getString(pathOrUrl) ?? '';
    if (cacheFirst) {
      if (body.isEmpty) {
        // debugPrint('noCached: $pathOrUrl,');
        var response =
            await http.get(Uri.parse(pathOrUrl + q), headers: headers);
        prefs.setString(pathOrUrl, response.body);
        prefs.setString('${pathOrUrl}_Last-Modified',
            response.headers['last-modified'] ?? '');
        return response.body;
      } else {
        // debugPrint('Cached: $pathOrUrl, body: ${body.substring(0, 20)}');
        var oldPath = pathOrUrl;
        http.get(Uri.parse(pathOrUrl + q), headers: headers).then(
          (response) {
            if (response.statusCode == 200) {
              prefs.setString(oldPath, response.body);
              prefs.setString('${oldPath}_Last-Modified',
                  response.headers['last-modified'] ?? '');
            } else {
              // debugPrint('notModified: $oldPath,');
            }
          },
        );
        return body;
      }
    } else {
      var response =
          await http.get(Uri.parse(pathOrUrl + q), headers: headers);
      if (response.statusCode > 299) {
        if (response.statusCode == 304) {
          return body;
        }
        return "fun build(){return Center(child: Text(\"${response.body}\"));}";
      }
      if (response.headers['last-modified'] != null) {
        prefs.setString(pathOrUrl, response.body);
        prefs.setString(
            '${pathOrUrl}_Last-Modified', response.headers['last-modified']!);
      }
      return response.body;
    }
  }
  return Future.value(
      "fun build(){return Center(child: Text(\"invalid url\"));}");
}