我有一个测验屏幕,其中我使用API
和FutureBuilder
。每次刷新build
方法时,获取新问题。底部有一个提交按钮,用于保存响应和重置屏幕。我想做的是disable
提交按钮,直到按下提交按钮后获取新问题,并在重建新问题时启用。我不能用bool变量调用setstate使其为null,因为新问题会因此而加载。下面是我的代码来重现这个问题:
import 'package:flutter/material.dart';
class QuizForm extends StatefulWidget {
const QuizForm({Key? key}) : super(key: key);
@override
State<QuizForm> createState() => _QuizFormState();
}
class _QuizFormState extends State<QuizForm> {
int buildCount = 0 ;
getQuestion () {}
@override
Widget build(BuildContext context) {
print(buildCount);
print('Question Fetched and UI is building');
return SafeArea(child: Scaffold(
body: FutureBuilder(
future: getQuestion(),
builder: (context, snapshot){
return ListView(
children: [
ListTile(title: Text('Quiz Title'),),
ListTile(title: Text('1'),),
ListTile(title: Text('2'),),
ListTile(title: Text('3'),),
ListTile(title: Text('4'),),
SizedBox(height: 20,),
ElevatedButton(
onPressed: () async {
print('Please Wait, Answer is getting Saved');
// Button Should be shown disabled for 3 seconds
await Future.delayed(const Duration(seconds: 3));
buildCount++;
setState(() {
// this setState rebuilds the screen and new question is loaded
// because of future builder
});
}, child: Text('Submit Quiz'))
],
);
},
),
));
}
}
1条答案
按热度按时间cclgggtu1#
从API获取数据时,检查变量中是否有数据,如果有数据则返回数据,否则调用API,
更新:具有_submitEnabled值。
以下为示例: