Flutter FutureBuilder不会更新

问题描述

我知道已经有一个类似的问题,但是我无法从其答案中真正解决我的问题。因此,我有一个FutureBuilder,它在加载数据时不会更新,我也不知道为什么。据我了解,延迟2秒后应重新构建小部件(应打印“数据已到达”)。为什么这没有发生?

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

    },),);
}
}

控制台输出为:

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

解决方法

您不应在自己的lamda中返回"Hello"

尝试

(){}