Tự học Flutter 2023

New Dart

Các câu lệnh điều khiển trong Dart

  • If và Else
  • For loop
  • While và do-while
  • Break và continue
  • Switch case
  • Assert
  • If và Else

                          
    void main() {
      var currentHour = DateTime.now().hour;
      if(currentHour > 12) {
        print("Good afternoon!");
      } else {
        print("Good morning!");
      }
    }
                          
                          

    For loop

                          
    var colors = ["green", "yellow", "brown", "pink"];
    
    void main() {
    
      // normal for loop
      for (int i = 0; i < colors.length; i++) {
        print(colors[i]);
      }
      
      // for - in 
      for (final color in colors) {
        print(color);
      }
      
      // foreach
      colors.forEach(print); // colors.forEach((color) => print(color));
    
    }
                          
                          

    While và do-while

                          
    void main() {
      var colors = ["green", "yellow", "brown", "pink"];
      var colorIndex = 0;
    
      while (colorIndex < colors.length) {
        // While kiểm tra điều kiện trước khi lặp
        print(colors[colorIndex]);
        colorIndex++;
      }
    }
                          
                          

                          
    void main() {
    
      var colors = ["green", "yellow", "brown", "pink"];
      var colorIndex = 0;
    
      do { // Do lặp trước mới kiểm tra điều kiện
        print(colors[colorIndex]);
        colorIndex++;
      } while (colorIndex < colors.length); 
    
    }
                          
                          

    Break và continue

    Sử dụng break để thoát khỏi vòng lặp.

                          
    var colors = ["green", "yellow", "brown", "pink"];
    void main() {
      for (final color in colors) {
        print(color);
        if (color == "yellow") {
          break;
        }
      }
    }
                          
                          

    Sử dụng câu lệnh continue bỏ qua các câu lệnh tiếp theo trong lần lặp hiện tại và đưa điều khiển trở lại đầu vòng lặp (bắt đầu vòng lặp tiếp theo).

                          
    var colors = ["green", "yellow", "brown", "pink"];
    void main() {
      for (final color in colors) {
        if (color == "brown") {
          continue;
        }
        print(color);
      }
    }
                          
                          

    Switch case

    Câu lệnh switch trong Dart so sánh các số nguyên, chuỗi hoặc hằng số comlile time bằng cách sử dụng ==. Tất cả các đối tượng được so sánh phải là các thể hiện của cùng một lớp (và không thuộc bất kỳ kiểu con nào của nó) và lớp không được ghi đè toán tử ==. Các kiểu enum cũng hoạt động tốt với switch.

    Mỗi mệnh đề case không trống kết thúc bằng một câu lệnh break, như một quy tắc. Cách hợp lệ khác để chấm dứt một case không rỗng là một câu lệnh continue, throw hoặc return.

    Sử dụng mệnh đề default để thực thi mã khi không có case nào khớp

                          
    void main() {
      var command = 'OPEN';
      switch (command) {
        case 'PENDING':
          executePending();
          break;
        case 'APPROVED':
          executeApproved();
          break;
        case 'DENIED':
          executeDenied();
          break;
        default:
          executeUnknown();
      }
    }
    
    void executePending() {}
    void executeApproved() {}
    void executeDenied() {}
    void executeUnknown() {}
                          
                          

    Ví dụ sau bỏ qua câu lệnh break trong mệnh đề case, do đó tạo ra lỗi:

                          
    void main() {
      var command = 'OPEN';
      switch (command) {
        case 'APPROVED':
          executeApproved();
        // ERROR: Missing break
    
        case 'DENIED':
          executeDenied();
          break;
      }
    }
    
    void executeApproved() {}
    void executeDenied() {}
    
                          
                          

    Tuy nhiên, Dart vẫn hỗ trợ các mệnh đề case trống , cho phép một hình thức fall-through:

                          
    void main() {
      var command = 'CLOSED';
      switch (command) {
        case 'CLOSED': // Empty case falls through.
        case 'NOW_CLOSED':
          // Runs for both CLOSED and NOW_CLOSED.
          executeNowClosed();
          break;
      }
    }
    
    void executeNowClosed() {}
                          
                          

    Nếu bạn thực sự muốn fall-through, bạn có thể sử dụng một lệnh continue kèm label:

                          
    void main() {
      var command = 'CLOSED';
      switch (command) {
        case 'CLOSED':
          executeClosed();
          continue nowClosed;
        // Continues executing at the nowClosed label.
    
        nowClosed:
        case 'NOW_CLOSED':
          // Runs for both CLOSED and NOW_CLOSED.
          executeNowClosed();
          break;
      }
    }
    
    void executeClosed() {}
    void executeNowClosed() {}
                          
                          

    Assert

    Trong quá trình phát triển, sử dụng hàm assert(condition, optionalMessage) để dừng sự thực thi bình thường nếu một điều kiện boolean là sai.

                          
    void main() {
      var number = 100;
      var urlString = "http://tuhocflutter.dev";
      // Make sure the value is less than 100.
      assert(number < 100);
    
      // Make sure this is an https URL.
      assert(urlString.startsWith('https'));
    }