0

I am fairly new to fluter, I've looked everywhere and found no solution to my error. I want to return the result print from an api call, but I am unable to. I end up getting "Instance of 'Future" instead of printing the List

The error which I keep getting

Instance of 'Future<List>'

My code

class _SuperVisorSheetState extends State<SuperVisorSheet> {
  Future <List> clusters;
  Future<List> getClusters() async{
    var response = await Dio().get('http://192.168.100.3:8080/api/v1/clustertable');
   return response.data;
  }

  @override
  void initState() {
    // TODO: implement initState
    clusters = getClusters();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xff392850),
        title: Text("Supervisor "),
      ),
      body: Container(
          padding: EdgeInsets.all(10),
          child: FutureBuilder<List>(
            future: clusters,
              builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
              if(snapshot.hasData){
                print(clusters);
                return Text("Hello");
              }
              return null;
              },
          )
blackbird
  • 460
  • 3
  • 9
  • 25

1 Answers1

1

First, you shouldn't return null from FutureBuilder. And to access the data you should use snapshot.data. Something like this:

FutureBuilder<List>(
    future: clusters,
    builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
        if (snapshot.hasData) {
            print("clusters: ${snapshot.data.join(", ")}");
            return Text("Hello");
        }
        return SizedBox();
    },
)
ChessMax
  • 2,125
  • 1
  • 16
  • 16
  • Hi @ChessMax, after adding that I end up with on error on this line, `clusters = await getClusters();`, the error is `A value of type 'List' can't be assigned to a variable of type 'Future>'` – blackbird Oct 30 '20 at 06:48
  • I've updated the answer, the previous answer was wrong, revert your code. – ChessMax Oct 30 '20 at 07:06
  • nothing is getting printed – blackbird Oct 30 '20 at 07:13
  • It's strange. Do you see "Hello" text on the screen? – ChessMax Oct 30 '20 at 07:18
  • no nothing is being displayed – blackbird Oct 30 '20 at 07:22
  • I've recreated your code and I see output and "Text" on display. Maybe the problem somewhere else. https://gist.github.com/ChessMax/c6359fb8cef089950939f3f38ac9a794 here is the code. You can copy it to https://dartpad.dev/flutter and run. You will see "Text" on the screen and output in the console – ChessMax Oct 30 '20 at 07:32
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223855/discussion-between-blackbird-and-chessmax). – blackbird Oct 30 '20 at 07:44