从列表中的url读取数据 [英] Reading data from url in List

查看:57
本文介绍了从列表中的url读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过以下方式从URL读取数据:

I know I can read data from URL as:

import 'dart:convert';
import 'dart:io';

new HttpClient().getUrl(Uri.parse('https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'))
          .then((HttpClientRequest request) => request.close())
          .then((HttpClientResponse response) => response.transform(new Utf8Decoder()).listen(print));

上面打印了我得到的答复.另外,我知道可以通过将最后一个语句替换为以下内容来将读取的字符串放入文件中:

Where the above print the response I'm getting. Also, I know that the read string can be put into a file by replacing the last statement to be:

.then((HttpClientResponse response) => response.pipe(new File('foo.txt').openWrite()));

另一方面,我知道我可以将字符串放入CSV中,如下所示:

In the other hand, I know I can put a string into CSV as:

// dependencies: csv: ^4.0.3
import 'package:csv/csv.dart';

List<List<dynamic>> rowsAsListOfValues = const CsvToListConverter().convert(yourString);

但是如何将它们组合在一起,以便如上所述使用 http 从url读取数据,并将返回的响应解码为 csv 变量?

But how can I combine them together, so that I read the data from url using http as shown above, and decode the returned response into csv variable?

推荐答案

我认为,如果您使用 async 标记您的方法,那么您将有一个更轻松的时间,以便您可以使用 await .then()方法.像这样:

I think you will have an easier time if you mark your method with async so you can use the await keyword instead of trying using the .then() method. So something like this:

import 'dart:convert';
import 'dart:io';
import 'package:csv/csv.dart';

Future<void> main() async {
  print(await csv());
}

Future<List<List<dynamic>>> csv() async {
  final request = await HttpClient().getUrl(Uri.parse(
      'https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'));
  final response = await request.close();
  final csvString = await response.transform(const Utf8Decoder()).first;
  return const CsvToListConverter().convert(csvString);
}

您可以在此处了解更多信息: https://dart.dev/codelabs/async-await

You can read more about this here: https://dart.dev/codelabs/async-await

这篇关于从列表中的url读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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