[英]Why the state of widgets is not changing on flutter?
I am using a variable column whose children has stateful methods, for example:我正在使用一个变量列,其子项具有有状态的方法,例如:
String word = 'hi';
Column c = Column(
children: [
FlatButton(
child(Text(word)),
onPressed() {
setState({
word += word;
})
}
) // Flat Button
]
);
but setState won't work for me, this is the full code:但 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
I have tried many other ways like putting it in a radio list with its own state builder but it didn't work, and when I press the buttons the number changes, here is a snapshot of the screen: questions form我尝试了许多其他方法,例如将其放入带有自己的 state 构建器的收音机列表中,但它不起作用,当我按下按钮时,数字会发生变化,这是屏幕快照:问题表格
I think you maintain the below variables inside the build
method.我认为您在
build
方法中维护以下变量。 So, It will initialize as a new element every time you (Rebuild) call setState((){})
.因此,每次您(重建)调用
setState((){})
时,它都会初始化为一个新元素。 It will work if you maintain the below variables outside of the build
method.如果您在
build
方法之外维护以下变量,它将起作用。
Column questionsForm;
Map answers = Map();
Map sortedQuestions;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.