Flutter定义StatefulWidget刷新问题解决
在Flutter定义StatefulWidget时,需要控制变量的值来更新UI,我最开始是这样写的:
List _getTabListWidget(){
List tabWidgets = [];
Color c = Color(0xff666666);
FontWeight weight = FontWeight.normal;
for(int i = 0;i < widget.tabs.length;i++){
if(_selectedIndex == i){
c = Color(0xff606FFF);
weight = FontWeight.w800;
}
tabWidgets.add(Text(widget.tabs[i],
textAlign:TextAlign.center,
style: TextStyle(
color: c,
fontWeight: weight,
fontSize: widget.fontSize,
)
));
}
return tabWidgets;
}
然后当用户点击Tab页时执行:预期效果是能够更细Text的颜色,但实际上没执行更新,原因是_selectedIndex没有绑定到Text()上。
setState(() {
_selectedIndex = index;
});
正确的写法是:
List _getTabListWidget(){
List tabWidgets = [];
for(int i = 0;i < widget.tabs.length;i++){
tabWidgets.add(Text(widget.tabs[i],
textAlign:TextAlign.center,
style: TextStyle(
color: _selectedIndex==i?Color(0xff606FFF):Color(0xff666666),
fontWeight: _selectedIndex==i?FontWeight.w800:FontWeight.normal,
fontSize: widget.fontSize,
)
));
}
return tabWidgets;
}
解决。
本站内容来源于作者发布和网络转载,如有版权相关问题请及时与我们取得联系,我们将立即删除。