【问题标题】:Flutter- Make the app show the previously fetched data when device is offlineFlutter - 让应用在设备离线时显示之前获取的数据
【发布时间】:2019-08-21 15:09:52
【问题描述】:

我是 Flutter 新手,需要一些帮助。我构建了一个随机笑话生成器应用程序,它从 API 读取数据并在每次按下按钮时显示一个新笑话。 我想让应用在设备离线时显示之前获取的数据。我尝试在线搜索,但没有找到使用 Flutter 的功能。

    class _HomePageState extends State<HomePage> {
  List data;
  Future<Jokes> post;
  String url="https://official-joke-api.appspot.com/random_joke";
  var response;
  Future<Jokes> getData() async {

     response =
        await http.get(url, headers: {"Accept": "application/json"});

     if (response.statusCode == 200) {
       return Jokes.fromJson(json.decode(response.body));
     } else {
       throw Exception('Failed to load post');
     }



  }

   changeApi()
  {
    setState(() {
      if (response.statusCode == 200) {
        return Jokes.fromJson(json.decode(response.body));
      } else {
        throw Exception('Failed to load post');
      }
    });
  }

@override

void initState()
{
  super.initState();
  this.getData();
}


  @override
  Widget build(BuildContext context) {
    final key = new GlobalKey<ScaffoldState>();
    // TODO: implement build
    return Scaffold(

      key: key,
      backgroundColor: Colors.amberAccent,
      body: new Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new FutureBuilder<Jokes>(
              future:
                  getData(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  //checks if the response returns valid data
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[

                        new GestureDetector(

                          child: new Text(
                            snapshot.data.setup ,
                            style: TextStyle(fontFamily: "Rock Salt"),
                          ),
                          onLongPress: ()
                          {
                            Clipboard.setData(new ClipboardData(text: snapshot.data.setup, ));
                            key.currentState.showSnackBar(
                                new SnackBar(content: new Text("Copied to Clipboard"),));
                          },
                        ),
                        /
                        SizedBox(
                          height: 10.0,
                        ),

                        new GestureDetector(

                          child: new Text(
                            " - ${snapshot.data.punchline}",
                            style: TextStyle(fontFamily: "Roboto"),
                          ),

                          onLongPress: ()
                          {

                            Clipboard.setData(new ClipboardData(text: snapshot.data.punchline));
                            key.currentState.showSnackBar(
                                new SnackBar(content: new Text("Copied to Clipboard"),));
                          },

                        ),

                      ],
                    ),
                  );
                } else if (snapshot.hasError) {
                  //checks if the response throws an error
                  return Text("${snapshot.error}");
                }
                return CircularProgressIndicator();
              },
            ),
            SizedBox(
              height: 25.0,
            ),
            new RaisedButton(
                onPressed: changeApi,
                color: Colors.pinkAccent,
                child: Text("Press for a new joke", style: TextStyle(color: Colors.white,)),
            )


          ],
        ),
      ),
    );
  }
}

class Jokes {
  final String setup;
  final String punchline;

  Jokes({this.setup, this.punchline});

  factory Jokes.fromJson(Map<String, dynamic> json) {
    return Jokes(setup: json['setup'], punchline: json['punchline']);
  }
} 

Api

这是我的完整代码:code

【问题讨论】:

  • 将您的代码等作为 MCVE stackoverflow.com/help/mcve 包含在问题中。这会让你得到更快的反应。在此处发布问题之前,还请遵循“如何提问”指南:stackoverflow.com/help/how-to-ask 如果您的问题不符合“如何提问”指南,请尝试初学者编程论坛和小组,这将比 SO 更有帮助。如果您的代码有精确的技术问题,请将其发布在 SO 上。如果您不遵循 SO 问题指南,您的问题可能会被否决或关闭,没有任何收获或回应。不过,您可以编辑您的问题以改进它。
  • 可以使用单源真实模式,看这篇文章:blog.usejournal.com/…

标签: android json api flutter


【解决方案1】:

有一些关于缓存的视频,一个来自flutter team,一个来自张量编程channel。

您可以使用connectivity插件检查设备是否离线。 如果设备离线,显示来自shared_preferences 或sqflite 的数据,如果设备在线,获取新数据(当然还要更新缓存)。

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2023-04-05
    • 1970-01-01
    • 2017-02-07
    相关资源
    最近更新 更多