Flutter FutureBuilder doesn't update

Issue

I know there is already a similar question, but i couldn’t really solve mine from its answers. So I have a FutureBuilder which won’t update when the data is loaded and I cant figure out why. The way I understand it, after the 2 second delay the Widget should be rebuild ("Data Arrived" should be printed). Why is this not happening?

import 'package:flutter/material.dart';

class NewQRPage extends StatefulWidget {
  @override
  _NewQRPageState createState() => _NewQRPageState();
}


class _NewQRPageState extends State<NewQRPage> {

Future link;

@override
void initState() {
  link = getLink();
  super.initState();
}

getLink() async{

  Future.delayed(Duration(milliseconds: 2000),(){
    print("Data Returned");
    return "hello";
  });

}

@override
Widget build(BuildContext context) {
  return Container(
    child: FutureBuilder(
    future: link,
    builder: (context, snapshot) {

      if(snapshot.hasData){
        print("Data Arrived");
        return Text(snapshot.data);
      }
      else if(snapshot.hasError){
        print("Error");
        return Text("Error");
      }
      else {
        print("No Data");
        return Text("No Data");
      }

    },
  ),
);
}
}

And the Console Output is:

Performing hot restart...
Syncing files to device LYA L29...
Restarted application in 1.044ms.
I/flutter (22206): onStartCalled
I/flutter (22206): No Data
I/flutter (22206): No Data
I/flutter (22206): No Data
I/flutter (22206): Data Returned

Solution

You shouldn’t return "Hello" in your lamda i.e (){}

Try

Future<String> getLink() async{
  await Future.delayed(Duration(milliseconds: 2000));
  print("Data Returned");
  return "hello";
}

Answered By – Josteve

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *