本文主要是介绍flutter刷新一个状态,来刷新控件的状态,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1,flutter定义一个状态值,应该放在哪里合适?
1.1, flutter widget的结构
//无状态的,固定widget
class CustomPositionedWidget extends StatelessWidget {const CustomPositionedWidget({super.key,});@overrideWidget build(BuildContext context) {return Container();}
}//有状态的widget
class CustomPositionedWidget extends StatefulWidget {//状态属性写在这里???const CustomPositionedWidget({super.key,});@override_CustomPositionedWidgetState createState() => _CustomPositionedWidgetState();
}class _CustomPositionedWidgetState extends State<CustomPositionedWidget> {//状态属性写在这里???@overridevoid initState() {super.initState();}@overrideWidget build(BuildContext context) {return Container();}
}
状态属性写在哪里合适?
enum AnswerState { unanswered, correct, incorrect }class CustomPositionedWidget extends StatefulWidget {//这里只是传递了初始值final bool initialNeedShowState;final AnswerState initialAnswerState;const CustomPositionedWidget({required this.initialNeedShowState,required this.initialAnswerState,});@override_CustomPositionedWidgetState createState() => _CustomPositionedWidgetState();
}class _CustomPositionedWidgetState extends State<CustomPositionedWidget> {//还是写在这里好,其实在这里也设置了初始值(默认值)bool _needShowState = false;AnswerState _answerState = AnswerState.unanswered;@overridevoid initState() {super.initState();//设置 构造函数传递过来的初始值_needShowState = widget.initialNeedShowState;_answerState = widget.initialAnswerState;}void updateState(bool needShowState, AnswerState answerState) {setState(() {//如果这两个值有改变,会重新绘制widget_needShowState = needShowState;_answerState = answerState;});}String getStr() {if (_answerState == AnswerState.correct) {return 'correct_image';} else if (_answerState == AnswerState.incorrect) {return 'incorrect_image';} else {return 'default_image';}}@overrideWidget build(BuildContext context) {return Positioned(right: 22.w,top: 0,bottom: 0,child: Align(alignment: Alignment.center,child: _needShowState && (_answerState != AnswerState.unanswered)? Image.asset(width: 36.w,height: 36.h,'assets/images/${getStr()}.png',fit: BoxFit.cover,): Container(),),);}
}
这篇关于flutter刷新一个状态,来刷新控件的状态的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!