dart - Flutter 如何将数据列表保存到本地存储
问题描述
我正在开发关于颤振的电影发现应用程序,我需要将正在播放的电影列表保存在本地存储中以供离线使用,那么我该如何做到这一点 Future> getNowPlayingMovies() async { final String nowPlaying = ' https://api. themoviedb.org/3/tv/airing_today?api_key='+'$myapikey'+'&page='+'1 ';
var httpClient = new HttpClient();
try {
// Make the call
var request = await httpClient.getUrl(Uri.parse(nowPlaying));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var jsonResponse = await response.transform(utf8.decoder).join();
// Decode the json response
var data = jsonDecode(jsonResponse);
// Get the result list
List results = data["results"];
print(results);
// Get the Movie list
List<moviemodel> movieList = createNowPlayingMovieList(results);
// Print the results.
return movieList;
} else {
print("Failed http call.");
}
} catch (exception) {
print(exception.toString());
}
return null;}
List<moviemodel> createNowPlayingMovieList(List data) {
List<Searchmodel> list = new List();
for (int i = 0; i < data.length; i++) {
var id = data[i]["id"];
String title = data[i]["name"];
String posterPath = data[i]["poster_path"];
String mediatype = data[i]["media_type"];
moviemodel movie = new moviemodel(id, title, posterPath, mediatype);
list.add(movie);
}
return list; }
List<Widget> createNowPlayingMovieCardItem(
List<moviemodel> movies, BuildContext context) {
// Children list for the list.
List<Widget> listElementWidgetList = new List<Widget>();
if (movies != null) {
var lengthOfList = movies.length;
for (int i = 0; i < lengthOfList; i++) {
Searchmodel movie = movies[i];
// Image URL
var imageURL = "https://image.tmdb.org/t/p/w500/" + movie.posterPath;
// List item created with an image of the poster
var listItem = new Padding(
padding: const EdgeInsets.all(8.0),
child: new Container(
width: 105.0,
height: 155.0,
child: new Column(
children: <Widget>[
new GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (_) => new Detail(movie.id)),
);
},
child: new Container(
width: 105.0,
height: 155.0,
child: new ClipRRect(
borderRadius: new BorderRadius.circular(7.0),
child: new Hero(
tag: movie.title,
child: new FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: imageURL,
fit: BoxFit.cover,
),
),
),
decoration: new BoxDecoration(boxShadow: [
new BoxShadow(
color: Colors.black12,
blurRadius: 10.0,
offset: new Offset(0.0, 10.0)),
]),
),
),
new Padding(
padding: const EdgeInsets.only(top: 18.0),
child: new Text(
movie.title,
maxLines: 2,
),
)
],
),
),
);
;
listElementWidgetList.add(listItem);
}
} else {
print("no movie search");
}
return listElementWidgetList;}
谢谢你!
解决方案
使用path_provider
:
- 找到正确的本地路径:
未来获取 _localPath 异步 { 最终目录 = 等待 getApplicationDocumentsDirectory(); 返回目录.路径; }
- 创建对文件位置的引用
未来获取 _localFile 异步 { 最终路径 = 等待 _localPath; 返回文件('$path/yourfile.txt'); }
- 将数据写入文件:
未来 writeCounter(int counter) async { 最终文件 = 等待 _localFile; // 写入文件 return file.writeAsString('blah bla blah'); }
- 从文件中读取数据:
未来的 readCounter() 异步 { 尝试 { 最终文件 = 等待 _localFile; // 读取文件 字符串内容 = 等待 file.readAsString(); 返回 int.parse(内容); } 抓住 (e) { // 如果遇到错误,返回 0 返回0; } }
如果你打印contents
= "blah blah blah"
文档:https ://flutter.io/cookbook/persistence/reading-writing-files/
File 有很多方法可以帮助你,结帐:
推荐阅读
- html - 你应该以什么顺序为同一个 HTML 元素声明“id”和“class”,为什么?
- android - 如何在 JSON 下面获取 Packing_charge 的 configurationVal?
- java - 在 Spring 项目中进行测试 - 使用 Mockito 将存储库注入服务
- elasticsearch - elasticsearch 字符串值 vs ids- 性能最佳实践
- java - Hibernate Spring Data 本机查询无法使用 MERGE INTO UPDATE set NULL
- sql - 在同一个表中比较一列
- android - 使用 Google Firebase 更新 SQLite 数据库
- vue.js - v-if 在 VueJS 组件上
- ionic-framework - ionic2+ 如何缓存页面,以便我可以导航到缓存页面的特定页面
- ios - 如何将参数中的 ID 发送到我的服务器?