【发布时间】:2020-02-10 22:16:41
【问题描述】:
我还是 Flutter 的新手。我想问一下为什么在void函数中不能使用setState()
这是我的代码:我的目标是滑块可以响应。上一个问题我仍然对使用 SetState void 函数感到困惑。所以首先当按下过滤器按钮时会出现一个弹出窗口,其中将显示几个类别的过滤器内容,然后在价格类别中有一个显示滑块的功能。我的滑块就像一个图像,无法更改。但是值变了
void _onButtonPressed1() {
//Function for Button Press "Sort"
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
color: Colors.black,
height: 500,
child: Container(
child: column1(),
decoration: BoxDecoration(
color: Colors.cyan[400],
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(30),
topRight: const Radius.circular(30),
)),
),
);
});}
new Expanded(
child: new Padding(
//padding overall filter include text&square
padding: EdgeInsets.fromLTRB(15, 0, 20, 0),
child: new Card(
color: Colors.transparent,
shape: const RoundedRectangleBorder(
side: BorderSide(
color: Colors.cyanAccent,
),
borderRadius: BorderRadius.all(Radius.circular(6.0)),
),
child: new RaisedButton(
child: new Row(children: <Widget>[
new Padding(
padding: EdgeInsets.fromLTRB(5.0, 0, 40, 0),
child: new Icon(Icons.format_align_left, color: Colors.cyanAccent),
),
new Text(
'Filter',
style: new TextStyle(
fontSize: 13,
color: Colors.cyanAccent,
),
),
]),
color: Colors.black,
padding: EdgeInsets.fromLTRB(1, 1, 1, 1),
onPressed: () => {
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
color: Colors.black,
height: 350,
child: Container(
// child: column(),
child: Wrap(
//dropdown button
children: <Widget>[
ListView.builder(
shrinkWrap: true,
itemCount: 3,
itemBuilder: (context, index) {
if (index < 2) {
final sort = _sort[index];
return ExpansionTile(
title: ListTile(
title: Text(
sort.category,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
),
children: <Widget>[ListTile(title: sort.item)],
);
} else {
return ExpansionTile(
title: ListTile(
title: Text(
'By Price',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
)),
children: <Widget>[
new RangeSlider(
min: 1,
max: 100,
divisions: 100,
values: values,
labels: labels,
onChanged: (value) {
print('START: ${value.start}, END: ${value.end}');
values = value;
labels = RangeLabels('${values.start.toInt().toString()}\$', '${values.end.toInt().toString()}\$');
setState(() {});
},
//Data from API
)
]);
}
}),
],
),
decoration: BoxDecoration(
color: Colors.cyan[400],
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(30),
topRight: const Radius.circular(30),
)),
),
);
},
)
}),
),
),
),
【问题讨论】:
-
请展示您的完整小部件代码并说明您想要完成的任务。因为 setState() 函数可以在 onPressed void 函数中使用。
-
我已经编辑了我的问题
-
您调用 setState() 方法的位置必须在您的小部件状态类中,而不是在某些外部函数中,并且您必须使用 StateFulWidget 而不是无状态小部件。
-
如果你的类是有状态的小部件,你可以使用 setState()