android - 如何在加载应用程序时存储未来数据以供进一步使用?# 颤动
问题描述
我是新来的颤振。我正在尝试为自己制作一个可以为我做一些计算的应用程序。
- 情况:当我启动应用程序时,它会从加载屏幕开始。在加载它时进行 API 调用以获取我将来需要的一些数据。并将其发送到我需要它的页面。这工作正常。
- 问题:我的应用程序中有多个页面。当我从任何其他页面返回主页时,数据消失了。所以我必须进行另一个 API 调用才能取回数据。我不希望这种情况发生
- 我想要什么:我希望在收到数据时将其存储在本地某个地方,以便我可以在任何我想要的地方使用它,而无需进行其他 API 调用或没有互联网连接。
我在做什么:
载入画面:
class Loading extends StatefulWidget {
@override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void setupPair() async
{
CurrInfo instance =
CurrInfo(url: 'EUR/USD', flagA: 'eur.png', flagB: 'usd.png');
await instance.getInfo();
if (instance.price != "not connected")
{
Navigator.pushReplacementNamed(context, '/home', arguments: {
'url': instance.url,
'flagA': instance.flagA,
'flagB': instance.flagB,
'price': instance.price,
});
} // I don't want to send this instance, instead I want to store the Received
data locally and access that data from anywhere inside the app
Video else if (instance.price == "not connected") {
Navigator.pushReplacementNamed(context, '/not connected');
}
}
通过api调用获取数据:
class CurrInfo {
String url;
String flagA;
String flagB;
String price;
String furl;
Map data;
List info;
CurrInfo({this.url, this.flagA, this.flagB});
Future<void> getInfo() async {
try {
print((url));
furl =
"https://fcsapi.com/api-v2/forex/latest?
symbol=$url&access_key=t58zo1uMFJZlNJxSrSmZv2qIUlSkCk9RAfCLkwnMwt1q1FFS";
Response response = await http
.get(Uri.encodeFull(furl), headers: {"Accept": "application/json"});
data = jsonDecode(response.body);
print(data);
info = data['response'];
print(info);
price = info[0]['price']; // I want to save this price data locally while loading so that I
don't have to make another API call to get it back and it should be
updated when I refresh the page
print("string price : $price");
} catch (e) {
price = "not connected";
print('error is : $e & $price');
}}}
我如何在需要的地方使用这些数据:
Map data = {};
String ofData;
Expanded(flex: 1,
child: Text( ${data['url']}',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold),
textAlign: TextAlign.start,
),
),
Expanded( flex: 1,
child: Text('${data['price']}',
style: TextStyle(fontSize: 18),
textAlign: TextAlign.end,
),
),
解决方案
你可以使用这个包 shared_preferences: ^0.5.12+2 在手机上本地存储数据
推荐阅读
- sql - 敏捷工具包 atk4 中的左连接和非 id 连接
- django - Django 服务器返回身份验证错误
- blazor - 在服务器端 Blazor 中登录后重定向
- android - 硬件后退按钮被调用两次
- pine-script - pinescript回测不同时间
- google-sheets - 当将数据从一张纸的单元格传输到另一张纸时,我得到#ref!错误。我该如何解决?
- python - 填充python数据框中缺少的日期列
- delphi - 如何访问元类引用的 TList 中的类变量?
- node.js - NextJS/Strapi 上传图片给特定用户
- git - 你如何进入 Alpine/git 容器?