FutureBuilder无法按预期工作

时间:2019-05-21 09:35:31

标签: android flutter

因此,我正在从我的flutter应用程序中从此处https://api.myjson.com/bins/1g3xpe获取json。

这是代码(我删除了不相关的部分)。问题是,FutureBuilder的生成器部分永远不会被调用。这行debugPrint(snapshot.hasData.toString());永远不会被调用。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:nirmithi/objects/project.dart';
import 'dart:convert';

class Projects extends StatefulWidget {
  @override
  ProjectsState createState() => new ProjectsState();
}

class ProjectsState extends State<Projects> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      primary: true,
      appBar: EmptyAppBar(),
      body: Column(
        children: <Widget>[
          headerWidget(),
          Container(
            child: futureBuilder(),
          )
        ],
      ),
    );
  }

  @override
  void setState(fn) {
    super.setState(fn);
  }
}

Future<List<Project>> getData() async {
  String getProjects = "https://api.myjson.com/bins/1g3xpe";

  final response = await http.get(getProjects);

  if (response.statusCode == 200) {
    List responseJson = json.decode(response.body);
    return responseJson.map((m) => Project.fromJson(m)).toList();
  } else
    throw Exception(response.toString());
}

Widget futureBuilder() {
  FutureBuilder<List<Project>>(
    future: getData(),
    builder: (context, snapshot) {
      debugPrint(snapshot.hasData.toString());
    },
  );

  return Center(
    child: CircularProgressIndicator(),
  );
}


Widget listWidget(List<Project> data) {
  return ListView.builder(
    itemCount: data.length,
    itemBuilder: (BuildContext context, int index) {
      listItem(data.elementAt(index));
    },
  );
}

Widget listItem(Project project) {

  return Card(
    elevation: 6.0,
    child: Column(
      children: <Widget>[Text(project.projectId), Text(project.projectName)],
    ),
  );
}

class EmptyAppBar extends StatelessWidget implements PreferredSizeWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  Size get preferredSize => Size(0.0, 0.0);
}

更新: 这是我已删除以进行调试的构建器部分中的代码。

switch (snapshot.connectionState) {
        case ConnectionState.none:
        case ConnectionState.waiting:
          return new Text('loading...');
        default:
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          else
            return listWidget(snapshot.data);
      }

1 个答案:

答案 0 :(得分:4)

您需要返回FutureBuilder,使其返回小部件树的一部分:

Widget futureBuilder() {
  return FutureBuilder<List<Project>>(
    future: getData(),
    builder: (context, snapshot) {
      // ...
    },
  );
}

仅创建它的实例并不能解决未来。