1

我知道已经有一个类似的问题,但我无法从它的答案中真正解决我的问题。所以我有一个 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
4

1 回答 1

2

你不应该"Hello"在你的 lamda 中返回,即(){}

尝试

Future<String> getLink() async{
  await Future.delayed(Duration(milliseconds: 2000));
  print("Data Returned");
  return "hello";
}
于 2020-09-04T14:22:42.690 回答