Вы можете сделать это, используя пакет quiver
, вот простой пример:
class QuizPage extends StatefulWidget {
@override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
final _formKey = GlobalKey<FormState>();
String answer;
int seconds;
@override
void initState() {
super.initState();
seconds = 60;
startTimer();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('QuizPage'),
),
body: Form(
key: _formKey,
child: Column(
children: <Widget>[
Text('Question?'),
Text('Seconds left: $seconds'),
TextFormField(
onSaved: (result) => answer = result,
),
RaisedButton(
child: Text('Answer!'),
onPressed: seconds != 0 ? (){
_formKey.currentState.save();
print(answer);
} : null,
)
],
),
),
);
}
void startTimer(){
CountdownTimer(Duration(seconds: seconds), Duration(seconds: 1)).listen((data){
})..onData((data){
setState(() {
seconds--;
});
})..onDone((){
setState(() {
seconds = 0;
});
});
}
}
Здесь вы можете ответить через 60 секунд, но когда время истекло, кнопка больше не будет работать.
И наоборот
Также вы можете рассчитать время от 0 и остановить таймер после ответа:
class QuizPage extends StatefulWidget {
@override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
final _formKey = GlobalKey<FormState>();
String answer;
Timer timer;
int seconds;
@override
void initState() {
super.initState();
seconds = 0;
timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
setState(() {
seconds++;
});
});
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('QuizPage'),
),
body: Form(
key: _formKey,
child: Column(
children: <Widget>[
Text('Question?'),
Text('Seconds passed: $seconds'),
TextFormField(
onSaved: (result) => answer = result,
),
RaisedButton(
child: Text('Answer!'),
onPressed:(){
timer?.cancel();
_formKey.currentState.save();
print(answer);
print('In $seconds seconds');
},
)
],
),
),
);
}
}