FlutterDart 如何让一个函数等待另一个独立函数完成?

问题描述 投票:0回答:1

我有一个开始和停止按钮和一个当前的状态是准备好或没有准备好。

当启动按钮被按下时,状态还没有准备好,只有在停止按钮被按下4秒后,状态才会准备好。如果在这4秒内,启动按钮被按下,我希望在停止功能将其设置为就绪后,状态马上变成 "未就绪"(所以本质上启动功能应该等待停止功能完成)。

以下是我试图解决这个问题的示例应用程序。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            isCurrentlyReady ? "ready" : "not ready",
            textAlign: TextAlign.center,
          ),
          if (canPressStart)
            CupertinoButton(
              child: Text('Start'),
              onPressed: start,
            )
          else
            CupertinoButton(
              child: Text('Stop'),
              onPressed: stop,
            )
        ],
      ),
    );
  }

  bool isCurrentlyReady = true;
  bool canPressStart = true;

  Future<bool> isReadyFuture = Future.value(true);

  start() async {
    setState(() {
      canPressStart = false;
    });
    await isReadyFuture;
    setState(() {
      isCurrentlyReady = false;
    });
    //this future will never come
    isReadyFuture = Future.delayed(Duration(days: 90000), () => true);
  }

  stop() async {
    setState(() {
      canPressStart = true;
    });
    await Future.delayed(Duration(seconds: 4));
    setState(() {
      isCurrentlyReady = true;
    });
    isReadyFuture = Future.value(true);
  }
}

我怎样才能达到预期的行为?

flutter asynchronous dart async-await future
1个回答
1
投票

在这里,你去。https:/codepen.iogazialankuspenNWGMYEe。

SO也要代码。给你

  Object token;
  bool isReady = false;

  void onStart() {
    setState(() {
      isReady = false;
    });
    token = null;
  }

  Future<void> onStop() async {
    Object myToken = Object();
    token = myToken;
    await Future.delayed(Duration(seconds: 4));
    if (token == myToken) {
      setState(() {
        isReady = true;
      });
      token = null;
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.