【问题标题】:How to show a widget while a asyncronous task is executing and then show a done widget after it has executed in flutter如何在异步任务执行时显示小部件,然后在颤振中执行后显示已完成的小部件
【发布时间】:2021-11-27 17:51:39
【问题描述】:

我想做一个异步加载对话框,从数据库中检索数据(这是异步任务),一旦完成,我想显示一个对话框,显示检索到的数据。 意思是,我想在从数据库中检索数据时显示一个加载对话框小部件,一旦检索到数据,就使用对话框将其显示在屏幕上

【问题讨论】:

  • 然后使用FutureBuilder
  • 但是如果在按钮单击@pskink 上调用未来的函数,我该怎么做

标签: flutter dart asynchronous async-await


【解决方案1】:

在这个我们需要处理树的场景,

  • 数据调用前,不显示任何内容
  • 在未来的通话中,显示进度条
  • 获取后,使用数据

使用两个可为空的变量来处理这种情况

只需根据需要更换小部件。

class _WelcomeScreenState extends State<WelcomeScreen> {
  Future<int> fecthData() async {
    return Future.delayed(
      Duration(seconds: 3),
    ).then(
      (value) => 4,
    );
  }

  bool? _isLoading;
  int? data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) => Column(
          children: [
            ElevatedButton(
                onPressed: () async {
                  setState(() {
                    _isLoading = true; //set true while fetching
                  });
                  data = await fecthData();
                  setState(() {
                    _isLoading = false; //set false while fetching
                  });
                },
                child: Text("Fetch")),
            if (_isLoading == true) CircularProgressIndicator(),
            if (data != null) Text("${data!}") // if you have data show it
          ],
        ),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 2023-03-07
    • 2020-07-29
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多