[英]What's the best of switching between widgets in Flutter?
hope that you're doing well!希望你一切都好!
I was just wondering, what is the best way for switching between widgets in Flutter?我只是想知道,在 Flutter 中的小部件之间切换的最佳方式是什么? For instance, let's say I'm asking the user 5 questions.例如,假设我要问用户 5 个问题。 What is the best way to move between the questions?在问题之间移动的最佳方式是什么? Should I make a separate screen for each one of the questions and navigate between them, keep a question index and use a switch statement to return the different questions, or is there something that is better and cleaner?我应该为每个问题制作一个单独的屏幕并在它们之间导航,保留一个问题索引并使用 switch 语句来返回不同的问题,还是有更好和更清晰的东西?
I'm currently using the index & switch statement approach and this is essentially what my code looks like:我目前正在使用 index & switch 语句方法,这基本上是我的代码的样子:
int questionIndex = 0;
Widget getQuestion(int index) {
Widget questionWidget;
switch (questionIndex) {
case 0:
questionWidget = Question0;
break;
case 1:
questionWidget = Question1;
break;
...
default:
questionWidget = Question0;
break;
}
return questionWidget;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: kLightGrey,
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(25.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
getQuestion(questionIndex),
MaterialButton(
child: Text('Next'),
onPressed: () {
questionIndex++;
},
),
],
),
),
),
);
}
}
You can also use PageView widget to add swipe gestures and animation when going to next/previous questions.在转到下一个/上一个问题时,您还可以使用 PageView 小部件添加滑动手势和 animation。
class MyHomePage extends StatelessWidget {
final PageController _controller = PageController();
@override
Widget build(BuildContext context1) {
return Scaffold(
body: Column(
children: [
Expanded(
child: PageView(
controller: _controller,
children: const [
Center(child: Text('Question 1')),
Center(child: Text('Question 2')),
Center(child: Text('Question 3')),
Center(child: Text('Question 4')),
Center(child: Text('Question 5')),
],
),
),
RaisedButton(
onPressed: () => _controller.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeIn,
),
child: const Text('Next'),
),
],
),
);
}
}
You can use loop your questions and use a ValueNotifier
for instance to update your Page depending on the question index contained in your variable您可以使用循环您的问题并使用ValueNotifier
例如根据变量中包含的问题索引来更新您的页面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.