gpt4 book ai didi

flutter - 在 Flutter 中存储缓存

转载 作者:行者123 更新时间:2023-12-03 09:40:34 24 4
gpt4 key购买 nike

我有一个用于获取 gmys 并将结果加载到 flutter 应用程序的 api。我希望 flutter 应用程序加载数据并存储在缓存中。当用户访问页面时,flutter应用程序应该检查是否有互联网连接,如果有,应该从在线api加载数据,如果没有互联网连接,它应该从缓存json文件加载。
目前,该应用程序仅在有互联网时才从在线 api 获取。
波纹管是我的代码:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class GymList extends StatelessWidget {
final String apiUrl ="apitogetgyms";

Future<List<dynamic>> fetchGyms() async {
var result = await http.get(apiUrl);
return json.decode(result.body)['gyms'];
}

String _name(dynamic gyms) {
return gyms['name'];
}


String _location(dynamic gyms) {
return gyms['location'];
}

String _phone(dynamic gyms) {
return gyms['phone'];
}

String _email(dynamic gyms) {
return gyms['email'];
}

String _img(dynamic gyms){
return gyms['img'];
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Gyms List'),
),
body: Container(
child: FutureBuilder<List<dynamic>>(
future: fetchGyms(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
//print(_name(snapshot.data[]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage:
NetworkImage(snapshot.data[index]['img'])),
title: Text(_name(snapshot.data[index])),
subtitle: Text(_location(snapshot.data[index])),
trailing: Text(_email(snapshot.data[index])),
)
],
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}

最佳答案

您可以通过使用 2 个包来实现此结果 shared_preferencesconnectivity .
使用连接,您可以检查您的连接状态并知道您是否可以访问互联网。

import 'package:connectivity/connectivity.dart';

final connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
// I am not connected.
} else {
// I am connected to internet.
}
然后使用 shared_preferences 您可以轻松保存您的 JSON 并在您未连接到互联网时加载它。
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

final jsonKey = 'json_key'; // Key used to save and get your data from SharedPreferences.
final prefs = await SharedPreferences.getInstance();

// Save your JSON as a String by encoding it.
await prefs.setString(jsonKey, jsonEncode(myJsonData));

// Get your JSON from SharedPreferences and decode it.
final json = jsonDecode(prefs.getString(jsonKey));
示例
import 'package:connectivity/connectivity.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

Future<List<dynamic>> fetchGyms() async {
final jsonKey = 'json_key';
final prefs = await SharedPreferences.getInstance();
final connectivityResult = await (Connectivity().checkConnectivity());

if (connectivityResult == ConnectivityResult.none) {
final json = jsonDecode(prefs.getString(jsonKey));
return json['gyms'];
} else {
final result = await http.get(apiUrl);
await prefs.setString(jsonKey, jsonEncode(result.body.toString()));
return jsonDecode(result.body)['gyms'];
}
}

关于flutter - 在 Flutter 中存储缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65019288/

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