【问题标题】:flutter async call doesn't run asynchronously in initState()颤振异步调用不会在 initState() 中异步运行
【发布时间】:2019-11-10 15:34:56
【问题描述】:

我在 initState() 中调用异步函数, 但系统实际上等待异步函数的结果。 谁能告诉我为什么?

这是我的代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: MyHomePage());
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<int> _f;

  @override
  void initState() {
    super.initState();
    Stopwatch stopwatch = new Stopwatch()..start();
    print('executed in ${stopwatch.elapsed}');
    _f = getFuture();
    print('executed in ${stopwatch.elapsed}');
  }

  Future<int> getFuture() async {
    int i = 0;
    while(i < 1000000000) {
      i++;
    }
    return i;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("test")),
      body: FutureBuilder<int>(
        future: _f,
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.done:
              return Center(child: Text("snapshot: ${snapshot.data}"));
              break;
            default:
              return Center(child: CircularProgressIndicator());
          }
        }

      ),
    );
  }
}

这是输出:

I/flutter (22058): executed in 0:00:00.000384
I/flutter (22058): executed in 0:00:04.536278

【问题讨论】:

标签: flutter future


【解决方案1】:

使Future 函数异步返回Future 对象。这意味着执行一次代码语句将花费更长的时间,例如从 api 获取 json 对象,而不是正常语句所需的通常时间,例如变量的声明。

但是,您正在执行一条正常的语句,需要几毫秒才能运行,1000000000 次。这将导致更长的执行时间,该时间由每次执行的毫秒数构成。

即使它是一个Future 函数,它也不会返回一个Future 对象或变量,因此它不是异步的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-01
    • 2022-06-19
    • 2019-01-29
    • 2019-05-07
    • 2021-06-29
    • 2020-12-09
    • 2020-02-16
    • 2021-09-18
    相关资源
    最近更新 更多