Flutter:serState()或markNeedBuild()在生成过程中调用


  • 我有一个小部件,它用来选择日期,一开始是"没有选择日期",下面一列中的小部件依赖于它[这意味着如果我选择了日期,它会显示数据的时间槽列表]

  • 但我在构建错误期间调用了一个setState,这个ReserveSlotWidget不能标记为需要构建,因为框架已经在构建小部件

  • 这是selectDate小部件

child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(
Icons.date_range,
color: Colors.white,
),
SizedBox(
width: 5,
),
Text(
_formatted == null
? 'No date chosen'
: _formatted,
style: TextStyle(
color: Colors.white,
))
],
),
FlatButton(
onPressed: ()=>_selectReservationDate(context),
child: Text(
'choose Date',
style: TextStyle(
color: Colors.white,
decoration: TextDecoration.underline),
),
)
],
),
if(_selectedDate != null)
Divider(
color: parseColor('#2A2E43'),
thickness: 2.0,
),
if(_selectedDate != null)
Row(
children: <Widget>[
Icon(
Icons.alarm,
color: Colors.white,
),
SizedBox(
width: 5,
),
Text('$_numberOfSeats Available Time Slots',
style: TextStyle(
color: Colors.white,
))
],
),
  • 这是一个列表视图项目,它的出现取决于我选择的日期

if(_formatted != null)

Expanded(
child: Consumer<SlotProvider>(
builder: (ctx, slotProvider, _)=>
ListView.builder(
itemCount: slotProvider.slots.length,
scrollDirection: Axis.horizontal,
itemBuilder: (ctx, index) {
setState(() {
_numberOfSeats = slotProvider.slots[index].seats;
});
return GestureDetector(
onTap: () {
setState(() {
if(_isInit){
_isExpanded = !_isExpanded;
}
_expandedIndex = index;
_isInit = false;
});
},
child: Container(
padding: EdgeInsets.all(4),
margin: EdgeInsets.all(4),
decoration: BoxDecoration(
color: _expandedIndex == index
? Theme.of(context).primaryColor
: parseColor('#2A2E43'),
borderRadius:
BorderRadius.all(Radius.circular(10))),
child: SlotsWidget(
fromTime: slotProvider.slots[index].fromTime.toString(),
toTime:slotProvider.slots[index].toTime.toString(),
seats:slotProvider.slots[index].seats,
))
);
}
),
)
),

@void的注释是正确的,您可以通过if块避免重复的setState;

if (_numberOfSeats != slotProvider.slots[index].seats)
setState(() {
_numberOfSeats = slotProvider.slots[index].seats;
});

相关内容

  • 没有找到相关文章

最新更新