我正在使用一个变量列,其子项具有有状态方法,例如:
String word = 'hi';
Column c = Column(
children: [
FlatButton(
child(Text(word)),
onPressed() {
setState({
word += word;
})
}
) // Flat Button
]
);
但是 setState 对我不起作用,这是完整的代码:
Widget build(BuildContext context) {
Column questionsForm;
Map answers = Map();
Map sortedQuestions;
return Scaffold(
backgroundColor: Colors.grey[200],
body: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(25.0),
child: Column(
children: [
StreamBuilder(
stream: partEnrollment.snapshots(),
builder: (context, snapshot) {
answers = Map();
questionsForm = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 25,
)
],
);
for (String q in questions.keys) answers[q] = -1;
for (String q in questions.keys) {
questionsForm.children.add(Text(
questions[q],
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
));
questionsForm.children.add(Row(
children: [
FlatButton(
onPressed: () {
setState(() {
answers[q] = 0;
print(answers[q]);
});
},
child: Text(
'Yes',
style: TextStyle(
fontSize: 17,
fontWeight:
answers[q] == 0 ? FontWeight.bold : FontWeight.normal),
),
),
FlatButton(
onPressed: () {
setState(() {
answers[q] = 1;
print(answers[q]);
});
},
child: Text(
'No',
style: TextStyle(
fontSize: 17,
fontWeight:
answers[q] == 1 ? FontWeight.bold : FontWeight.normal),
),
)
],
));
}
}
return questionsForm;
},
), //Stream builder
我尝试了许多其他方法,例如将其放入带有自己的状态构建器的单选列表中,但是没有用,当我按下按钮时,数字会发生变化, 这是屏幕快照: questions form
答案 0 :(得分:0)
我认为您在 build
方法中维护了以下变量。因此,每次您(重建)调用 setState((){})
时,它都会初始化为一个新元素。如果您在 build
方法之外维护以下变量,它将起作用。
Column questionsForm;
Map answers = Map();
Map sortedQuestions;