Flutter 2.10 - If else statement, Split widget
1, If else statement:
body: questionIndex < questions.length
? Column(
children: [
Question(
questions[questionIndex]['questionText'].toString(),
),
...(questions[questionIndex]['answer'] as List<String>)
.map((answer) {
return Answer(answerQuestion, answer);
}).toList()
],
)
: Center(child: Text('You did it')),
Toán tử ba ngôi : variable_name = (condition) ? value1 : value2
Nếu condition đúng thì var = value1 nếu sai thì var = value2.
Trong đoạn code trên nếu questionIndex < questions.length thì thực thi đoạn code trong block 1 ( từ ? đến :). Ngược lại, thực hiện block 2 (sau :).
2, Split widget:
Như đoạn code ở trên, việc đọc code sẽ khó khăn nếu là dự án thực tế. Trong flutter, chúng ta có thể bóc tách các widget to thành các widget nhỏ để dễ quản lý,... (Khuyến khích nên bóc ra các widget nhỏ nếu có thể). Nó tương tự với việc tách các đoạn code thành các function xử lý các nhiệm vụ khác nhau trong java.
Chúng ta có thể tách đoạn code trên thành như sau:
main.dart:
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: _questionIndex < _questions.length
? Quiz(questions: _questions, answerQuestion: _answerQuestion, questionIndex: _questionIndex)
: Result(),
),
);
}
* Đoạn toán tử ba ngôi đã dễ đọc hiểu hơn.
quiz.dart:
class Quiz extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function()? answerQuestion;
Quiz(
{required this.questions,
required this.answerQuestion,
required this.questionIndex});
@override
Widget build(BuildContext context) {
return Column(
children: [
Question(
questions[questionIndex]['questionText'].toString(),
),
...(questions[questionIndex]['answer'] as List<String>).map((answer) {
return Answer(answerQuestion, answer);
}).toList()
],
);
}
}
result.dart
class Result extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: Text('You did it'));
}
}
Nhận xét
Đăng nhận xét