FutureBuilder not workin as intended in flutter

So, I am fetching json from here: https://api.myjson.com/bins/1g3xpe, in my flutter app.

Here is the code (I have removed unrelated part).The issue is, FutureBuilder's builder part is never getting called. This line debugPrint(snapshot.hasData.toString()); is never getting called.

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);
}

UPDATE: This is the code in builder part which I removed to debug.

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 answer

  • answered 2019-05-21 10:21 SwiftingDuster

    You need to return your FutureBuilder so its part of the widget tree:

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

    Simply creating an instance of it wouldn't resolve the future.