Flutter 2.8 - Map, List, Callback

Code:
main.dart:
import 'package:flutter/material.dart';

import './answer.dart';
import './question.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}
}

class MyAppState extends State<MyApp> {
var questionIndex = 0;

void answerQuestion() {
setState(() {
questionIndex = questionIndex + 1;
});
if (questionIndex <= 3) {
print(questionIndex);
} else {
questionIndex = 0;
print('Out of range question?');
}
}

@override
Widget build(BuildContext context) {
var questions = [
{
'questionText': 'What\'s your favorite color ?',
'answer': ['Black', 'Red','Blue','Green']
},
{
'questionText': 'What\'s your favorite animals ?',
'answer': ['God','Cat','Goat','Mickey']
},
{
'questionText': 'What\'s your favorite club ?',
'answer': ['MU','MC','Real','Barca']
},
{
'questionText': 'What\'s your favorite sing ?',
'answer': ['Gio','Mua','U la troi' ,'Em cua ngay hom qua']
},
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(
questions[questionIndex]['questionText'].toString(),
),
...(questions[questionIndex]['answer'] as List<String>)
.map((answer) {
return Answer(answerQuestion, answer);
}).toList()
],
),
),
);
}
}


question.dart:
import 'package:flutter/material.dart';

class Question extends StatelessWidget {
final String questionText; // nếu k khai báo final => questionText có th thay đi => extends StatefullWidget

Question(this.questionText); // constructor

@override
Widget build(BuildContext context) {
return Container(
width: double.infinity, // t đng ly width rng nht có th
margin: EdgeInsets.all(10), // khong cách xung quanh container ( khong cách t container đến boder)
padding: EdgeInsets.only(bottom: 100), // khong cách t container đến child
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}


anwers.dart:
import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
final Function()? selectHandler;
final String answerText;
Answer(this.selectHandler, this.answerText);

@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
child: Text(answerText) ,
textColor: Colors.white,
color: Colors.blue,
onPressed: selectHandler,
),
);
}
}


Explain:
*Callback:
final VoidCallback selectHandler;
hoặc
 final Function()? selectHandler;
là callback event để comunicate giữa các widget trong flutter


*List<Map<String, Object>>
var questions = [
{
'questionText': 'What\'s your favorite color ?',
'answer': ['Black', 'Red','Blue','Green']
},]



*Lấy question:
Question(
questions[questionIndex]['questionText'].toString(),
),
questions : là 1 list dạng List<Map<String, Object>>
questionsIndex : vị trí của question muốn lấy trong list question
'questionText' : key để xác định vị trí cần lấy trong map



*Lấy answer:
...(questions[questionIndex]['answer'] as List<String>)
.map((answer) {
return Answer(answerQuestion, answer);
}).toList()

... : toán tử spread: lấy hết các phần tử trong 2 list  => hợp nhất single list :v

(questions[questionIndex]['answer'] as List<String>).map((answer): Lấy ds answer trong list questions - as List<String> sau đó map với answer



Trong Dart 2.3 update vào 19/4/2019 có toán tử " ?... ". Ví dụ
List lowerNumbers = [1, 2, 3, 4, 5];
List upperNumbers = [6, 7, 8, 9, 10];
List numbers = […lowerNumbers?…upperNumbers];

Nó tương đương với:

List numbers = [];
numbers.addAll(lowerNumbers);
if(upperNumbers != null){
 numbers.addAll(upperNumbers);
}


Toán tử Null-aware để đảm bảo null safe trong quá trình thực thi code, ví dụ như sau:
void main() {
  x = y ?? z; // nếu y null thì gán y cho x, không thì gán z cho x.

  var x = null;
  x ??= 'Syntax sugar của `x = x ?? "Viết gì vào đây bây giờ"`';
  print(x);

  var isNull = null;
  print(isNull?.foo()); // Nếu null thì không thực hiện foo() nữa mà trả về `null`
}





Nhận xét

Bài đăng phổ biến từ blog này

Flutter 4.5 - Custom theme, font, image

Flutter 1.2 - Flutter Architecture

Flutter 2.5 - First App | Building a Widget Tree