我有一个Flutter应用,有2页。第一页是一个简单的InkWell,它会将用户发送到第2页。点击第2页时,计时器应该每秒减少一次。而不是开始增量,它冻结。

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


int _time = 60;
bool _restart = false;

class MainPage extends StatefulWidget {
  @override
  MainPageState createState() => new MainPageState();
}

class MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
      return new Material(
      color: Colors.greenAccent,
      child: new InkWell(
        onTap: () {
          setState((){
            while ( true ) {
              sleep(const Duration(seconds:1));
              _time = _time - 1;
            }
          });
        },
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(_time.toString(), style: new TextStyle(color:
Colors.white, fontSize: 60.0, fontWeight: FontWeight.bold)),
          ]
        ),
      ),
    );
  }
}

最佳答案

那是因为您处于无限循环中,更好的方法是利用Timer:

  class TimerSample extends StatefulWidget {
    @override
    _TimerSampleState createState() => _TimerSampleState();
  }

  class _TimerSampleState extends State<TimerSample> {
    int _time = 60;
    bool _restart = false;
    Timer timer;

    _onTap() {
      if (timer == null) {
        timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
          _time = _time - 1;

          //your conditions here
          //call setState if you want to refresh the content
        });
      }
    }

    @override
    void dispose() {
      if (timer != null) {
        timer.cancel();
      }
      super.dispose();
    }

    @override
    Widget build(BuildContext context) {
      return new Material(
        color: Colors.greenAccent,
        child: new InkWell(
          onTap: _onTap,
          child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(_time.toString(),
                    style: new TextStyle(
                        color: Colors.white,
                        fontSize: 60.0,
                        fontWeight: FontWeight.bold)),
              ]),
        ),
      );
    }
  }

09-25 19:16