首页 > 解决方案 > 如何在加载应用程序时存储未来数据以供进一步使用?# 颤动

问题描述

我是新来的颤振。我正在尝试为自己制作一个可以为我做一些计算的应用程序。

  1. 情况:当我启动应用程序时,它会从加载屏幕开始。在加载它时进行 API 调用以获取我将来需要的一些数据。并将其发送到我需要它的页面。这工作正常。
  2. 问题:我的应用程序中有多个页面。当我从任何其他页面返回主页时,数据消失了。所以我必须进行另一个 API 调用才能取回数据。我不希望这种情况发生
  3. 我想要什么:我希望在收到数据时将其存储在本地某个地方,以便我可以在任何我想要的地方使用它,而无需进行其他 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,
      ),
    ),

在此处查看完整代码以更好地理解

标签: androiddatabaseandroid-studioflutterflutter-layout

解决方案


你可以使用这个包 shared_preferences: ^0.5.12+2 在手机上本地存储数据


推荐阅读