我是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']);
}
}
这是我的完整代码:code
答案 0 :(得分:0)
有一些有关缓存的视频,这是flutter team的视频,以及张量编程channel的视频。
您可以使用connectivity插件检查设备是否离线。 如果设备离线,则显示shared_preferences或sqflite中的数据;如果设备在线,则获取新数据(当然还要更新缓存)。