我有一个用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;
  }
}

但似乎没有执行网络部分.

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()个调用链来实现这一点,但是使用async/await的IMO可读性要好得多.

一旦有了返回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 列表中的 addAll() 和 followBy() 有什么区别?

PageView.builder 给出水平视口被给出无界高度错误

读取有状态(Stateful)小部件的状态

如何实现 Iterable

那么在 Flutter 中缓存最简单的方法是什么?

Flutter 中的 authStateChanges

如何go 除字符串中的变音符号?

Flutter:可重新排序和动画的 ListView - 有什么 idea 吗?

更改底片的灰色覆盖背景

如何从JSON对象获取格式化/缩进的JSON字符串?

判断Dart中是否提供了可选参数

如何使用flatter删除Firestore文档中的字段

如何减少 ListView.builder 中 RaisedButton 的宽度?

Dart 有 int.INFINITY 吗?

Opa vs Dart vs Haxe vs CoffeeScript

如何在 timeLimit 之后使future 的计算超时?

_internal 的语义是什么?

有没有办法在 Dart 中通过引用传递原始参数?

如何在 Dart 中将日期/时间字符串转换为 DateTime 对象?

将方法或值添加到 dart 中的枚举