gpt4 book ai didi

dart - 如何在 Dart 语言中将 Future 转换为 List

转载 作者:IT老高 更新时间:2023-10-28 12:33:01 31 4
gpt4 key购买 nike

我对使用 dart 语言进行编码有疑问。如何将 Future 转换为普通 List?在我的程序中,我需要来自网络的结果才能继续下一步,但我不知道该怎么做。就我而言,我需要将变量“data”的值作为列表返回。

class _MyAppState extends State<MyApp> {
static List getList() {
var url = "http://watcherman.cn/web/json.php";
var data;
HttpClient client = new HttpClient();
client.getUrl(Uri.parse(url))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.transform(UTF8.decoder).listen((contents) {
String jsonContent = contents.toString();
data = JSON.decode(jsonContent);
});
});
return data;
}
}

但似乎没有执行网络部分。 flutter 的代码部分似乎无法接受 Future。

class _MyAppState extends State<MyApp> {
static List content = getList();
@override
Widget build(BuildContext context) {
return new Container(
child: new ListView.builder(
scrollDirection: Axis.vertical,
padding: new EdgeInsets.all(6.0),
itemCount: content.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
alignment: FractionalOffset.center,
margin: new EdgeInsets.only(bottom: 6.0),
padding: new EdgeInsets.all(6.0),
color: Colors.blueGrey,
child: new Text(content[index]["title"])
);
}
)
);
}
}

最佳答案

你应该重写你的getList返回 Future<List> 的方法.可以使用 then() 的链来执行此操作调用,但 IMO 更易读 async / await .

一旦你有一个返回 Future<List> 的方法, 你可以使用 FutureBuilder 构建一个依赖于异步计算结果的树。

screenshot

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'dart:async';

void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}

class MyApp extends StatefulWidget {
State createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

static Future<List> getList() async {
var url = "http://watcherman.cn/web/json.php";
HttpClient client = new HttpClient();
HttpClientRequest request = await client.getUrl(Uri.parse(url));
HttpClientResponse response = await request.close();
return response.transform(UTF8.decoder).transform(JSON.decoder).toList();
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Futures Demo'),
),
body: new FutureBuilder(
future: getList(),
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
if (!snapshot.hasData)
return new Container();
List content = snapshot.data[0];
return new ListView.builder(
scrollDirection: Axis.vertical,
padding: new EdgeInsets.all(6.0),
itemCount: content.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
alignment: FractionalOffset.center,
margin: new EdgeInsets.only(bottom: 6.0),
padding: new EdgeInsets.all(6.0),
color: Colors.blueGrey,
child: new Text('${content[index]['title']}'),
);
},
);
}
)
);
}
}

关于dart - 如何在 Dart 语言中将 Future<List<Map> 转换为 List<Map>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297839/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com