Таймер управления в флаттере - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь установить одно логическое значение false через 2 секунды (showSpinner), но не могу с этим справиться, основная идея - показать загрузку счетчика в течение 2 секунд после отображения решения, но счетчик никогда не останавливается и решение никогда не появляется (счетчик загрузка счетчика, текст = решение) enter image description here

@override
  void initState(){
    super.initState();
    showSpinner=true;

      Timer(Duration(seconds: 2),(){
        setState(() {
          showSpinner=false;
        });
      });

  }

Widget build(BuildContext context) {


     Widget child;
      if (showSpinner == true && isPressed4 == true) {
        setState(() {
          Timer(Duration(seconds: 2), () {
            showSpinner == false;
          });
        });

        child = spinkit;
      }

      if (showSpinner == false && isPressed4 == true) {
        text = simpleInterest.accumulationFunction(
            time, yearlySimpleInterestRate, principal);
        child = Text(
          text,
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.center,
        );
      }

есть 3 кнопки (isPressed1 для кнопки 1 и isPressed2 для button2 и isPressd3 для кнопки 3, если все true isPressed4 становится истинным )

 var floatingActionButton1 = FloatingActionButton(
          onPressed: () {
            setState(() {
              isPressed1 = !isPressed1;
            });
            setState(() {
              principal = double.parse(_principalController.text);
            });
            setState(() {
              if (isPressed3 == true && isPressed2 == true && isPressed1 == true) {
                isPressed4 = true;
              }
            });
          },
          elevation: 40,
          backgroundColor: isPressed1 ? Colors.lightGreenAccent : null,
          heroTag: "btn1",
          child: Icon(Icons.check),
        );

Ответы [ 2 ]

1 голос
/ 06 апреля 2020

Я не знаю, что такое spinkit и isPressed4, но я бы сделал это так:

  bool showSpinner;

  @override
  void initState() {
    super.initState();
    showSpinner = true;

    Timer(Duration(seconds: 2), () {
      setState(() {
        showSpinner = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Title'),
        ),
        body: buildBody()
    );
  }

  Widget buildBody(){
    return showSpinner ?
    CircularProgressIndicator() :
    Text(
      'The answer',
    );
  }

UPD:

Первоначально У меня есть 2 секунды. Тогда:

  • Если showSpinner == false и floatingActionButton1 не были нажаты, то я получаю текст The time is up!.
  • Если showSpinner == true и floatingActionButton1 не были нажаты , тогда я получаю текст Button 4 is not pressed yet.
  • Если были нажаты showSpinner == true и floatingActionButton1, то я получаю CircularProgressIndicator() (как в вопросе).
  • Если были нажаты showSpinner == false и floatingActionButton1, тогда я получаю Text с The answer (как в вопросе):
  bool showSpinner;

  var floatingActionButton1;

  bool isPressed1;
  bool isPressed2;
  bool isPressed3;
  bool isPressed4;

  @override
  void initState() {
    super.initState();
    showSpinner = true;

    isPressed1 = false;
    isPressed2 = true;
    isPressed3 = true;
    isPressed4 = false;

    floatingActionButton1 = FloatingActionButton(
      onPressed: () {
        setState(() {
          isPressed1 = !isPressed1;

          if (isPressed3 == true && isPressed2 == true && isPressed1 == true) {
            isPressed4 = true;
          }
        });
      },
      backgroundColor: isPressed1 ? Colors.lightGreenAccent : null,
      child: Icon(Icons.check),
    );

    Timer(Duration(seconds: 2), () {
      setState(() {
        showSpinner = false;
      });
    });
  }


  Widget build(BuildContext context) {
    Widget child;

    if(showSpinner == false && isPressed4 == false)
      child = Text('The time is up!');

    else if(showSpinner == true && isPressed4 == false)
      child = Text('Button 4 is not pressed yet');

    else if (showSpinner == true && isPressed4 == true) {
      child = CircularProgressIndicator();
    }

    else if (showSpinner == false && isPressed4 == true) {
      child = Text(
        'The answer',
        style: TextStyle(fontSize: 18),
        textAlign: TextAlign.center,
      );
    }

    return Scaffold(
        appBar: AppBar(
          title: Text('Title'),
        ),
        body: child,
      floatingActionButton: floatingActionButton1,
    );
  }

0 голосов
/ 07 апреля 2020
void startTimer() {
      const oneSec = const Duration(seconds: 1);
      _timer = new Timer.periodic(
        oneSec,
        (Timer timer) => setState(
          () {
            if (_start ==0) {
              showSpinner=false;
              timer.cancel();
            } else {
              _start = _start - 1;
            }
          },
        ),
      );
    }

    @override
    void dispose() {
      _timer.cancel();
      super.dispose();
    }

решено с помощью этой функции и изменения таких кнопок, как;

var floatingActionButton1 = FloatingActionButton(
          onPressed: () {
            setState(() {
              isPressed1 = !isPressed1;
            });
            setState(() {
              principal = double.parse(_principalController.text);
            });
            setState(() {
              if (isPressed3 == true && isPressed2 == true && isPressed1 == true) {
                isPressed4 = true;
                startTimer();
              }
            });
          },
          elevation: 40,
          backgroundColor: isPressed1 ? Colors.lightGreenAccent : null,
          heroTag: "btn1",
          child: Icon(Icons.check),
        );
...