dart - 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)),
]),
),
);
}
}
推荐阅读
- html - Chromium 列布局和溢出隐藏隐藏文本
- syntax - BNF中语言的语法,如何指示“其他类似”选项
- python - 如何在没有预签名 URL 的情况下处理对 S3 的 html 文件输入
- sas - 如何在 SAS 中传递参数(以宏的形式)
- apache-kafka - kafka + 如何使用 kafka cli 作为 kafka-configs 更改主题保留时间
- javascript - 如何在网页中渲染 Blender 模型?
- flutter - 颤动无法从网络加载图像
- dart - 如何将最新的流映射组合成值映射?
- swiftui - SwiftUI 中的自定义交叉阴影背景形状或视图
- tabula - 在远程服务器上设置 Tabula