Flutter如何将数据列表保存到本地存储 [英] Flutter How to save list of data to local Storage

查看:1488
本文介绍了Flutter如何将数据列表保存到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发电影发现应用程序,因此需要将正在播放的电影列表保存在本地存储中以供离线使用,所以我该怎么办
Future> getNowPlayingMovies()async {
final String nowPlaying =
' https://api.themoviedb.org/ 3 / tv / airing_today?api_key = '+
'$ myapikey'+
'& page ='+
'1';

I am developing movie discovering app on flutter and I need to save the list of now playing movies on local storage for offline use and so how can I do that 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


  1. 找到正确的本地路径:





    Future get _localPath async {
      final directory = await getApplicationDocumentsDirectory();
      return directory.path;
    }




  1. 创建对文件位置的引用





    Future get _localFile async {
      final path = await _localPath;
      return File('$path/yourfile.txt');
    }




  1. 将数据写入文件:





    Future writeCounter(int counter) async {
      final file = await _localFile;

      // Write the file
      return file.writeAsString('blah bla blah');
    }




  1. 从文件中读取数据:





    Future readCounter() async {
      try {
        final file = await _localFile;

        // Read the file
        String contents = await file.readAsString();

        return int.parse(contents);
      } catch (e) {
        // If we encounter an error, return 0
        return 0;
      }
    }

如果打印内容 =等等等等

If you print contents = "blah blah blah"

文档: https://flutter.io/cookbook/persistence/reading-writing-files/

并且文件有一个许多方法可以帮助您,结帐:

https://docs.flutter.io/flutter/dart-io/File-class.html

这篇关于Flutter如何将数据列表保存到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆