ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Dart.dev Language samples
    Development/Flutter & Dart 2021. 2. 2. 22:50
    반응형

    Hello World

    Every app has a main() function. To display text on the console, you can use the top-level print() function:

    모든 앱은 main() 함수를 지닙니다. console에 텍스트를 표시하기 위해서 top-level print() 함수를 사용할 수 있습니다.

    void main() {
      print('Hello, World!');
    }

     

    Variables

    Even in type-safe Dart code, most variables don’t need explicit types, thanks to type inference:

    type-safe Dart 코드에서는 type inference 덕분에 대부분의 변수들은 명백한 type이 필요없습니다.

    var name = 'Voyager I';
    var year = 1977;
    var antennaDiameter = 3.7;
    var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
    var image = {
      'tags': ['saturn'],
      'url': '//path/to/saturn.jpg'
    };

    Read more about variables in Dart, including default values, the final and const keywords, and static types.

    디폴트 값과 final and const 키워드, static types을 포함한 Dart의 변수에 관하여 더 알아보세요.

     

    Control flow statements

    Dart supports the usual control flow statements:

    Dart는 control flow statements 를 지원합니다.

    if (year >= 2001) {
      print('21st century');
    } else if (year >= 1901) {
      print('20th century');
    }
    
    for (var object in flybyObjects) {
      print(object);
    }
    
    for (int month = 1; month <= 12; month++) {
      print(month);
    }
    
    while (year < 2016) {
      year += 1;
    }

    Read more about control flow statements in Dart, including break and continue, switch and case, and assert.

    breakd and continue, switch and case, and assert을 포함한 Dart의 control flow statements에 대해 더 알아보세요.

     

    Functions

    We recommend specifying the types of each function’s arguments and return value:

    우리는 함수의 인자와 리턴 값의 type을 특정하는 것을 추천합니다.

    int fibonacci(int n) {
      if (n == 0 || n == 1) return n;
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
    
    var result = fibonacci(20);

    A shorthand => (arrow) syntax is handy for functions that contain a single statement. This syntax is especially useful when passing anonymous functions as arguments:

    arrow syntax 는 한 줄짜리 함수를 포함할 때 아주 유용합니다. 특히 anonymous 함수를 인자로 보낼 때 말이죠.

    flybyObjects.where((name) => name.contains('turn')).forEach(print);

    Besides showing an anonymous function (the argument to where()), this code shows that you can use a function as an argument: the top-level print() function is an argument to forEach().

    Read more about functions in Dart, including optional parameters, default parameter values, and lexical scope.

     

    Comments

    Dart comments usually start with //.

    Dart의 코멘트는 보통 //로 시작합니다.

    // This is a normal, one-line comment.
    
    /// This is a documentation comment, used to document libraries,
    /// classes, and their members. Tools like IDEs and dartdoc treat
    /// doc comments specially.
    
    /* Comments like these are also supported. */

    Read more about comments in Dart, including how the documentation tooling works.

    Documentation tooling이 어떻게 작동하는지를 포함한 Dart의 코멘트에 대하여 더 알아보세요.

    Imports

    To access APIs defined in other libraries, use import.

    다른 라이브러이에서 정의된 API에 접근하기 위해서는 import를 사용하세요.

    // Importing core libraries
    import 'dart:math';
    
    // Importing libraries from external packages
    import 'package:test/test.dart';
    
    // Importing files
    import 'path/to/my_other_file.dart';

    Read more about libraries and visibility in Dart, including library prefixes, show and hide, and lazy loading through the deferred keyword.

     

    Classes

    Here’s an example of a class with three properties, two constructors, and a method. One of the properties can’t be set directly, so it’s defined using a getter method (instead of a variable).

    여기 세 개의 proprerty와 두 개의 constructor와 하나의 method를 가진 class 예제가 있습니다.

    한 property는 바로 set할 수 없어서 변수 대신 getter method를 사용했습니다.

    class Spacecraft {
      String name;
      DateTime launchDate;
    
      // Constructor, with syntactic sugar for assignment to members.
      Spacecraft(this.name, this.launchDate) {
        // Initialization code goes here.
      }
    
      // Named constructor that forwards to the default one.
      Spacecraft.unlaunched(String name) : this(name, null);
    
      int get launchYear =>
          launchDate?.year; // read-only non-final property
    
      // Method.
      void describe() {
        print('Spacecraft: $name');
        if (launchDate != null) {
          int years =
              DateTime.now().difference(launchDate).inDays ~/
                  365;
          print('Launched: $launchYear ($years years ago)');
        } else {
          print('Unlaunched');
        }
      }
    }

    You might use the Spacecraft class like this:

    당신은 Spacecraft class를 이렇게 사용할 수 있습니다.

    var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
    voyager.describe();
    
    var voyager3 = Spacecraft.unlaunched('Voyager III');
    voyager3.describe();

    Read more about classes in Dart, including initializer lists, optional new and const, redirecting constructors, factory constructors, getters, setters, and much more.

    initializer lists, optional new and const, redirecting constructors, factory constructors, getters, setters 등을 포함한 Dart의 class에 대해 더 알아보세요.

    Inheritance

    Dart has single inheritance.

    Dart는 하나의 inheritance를 지닙니다.

    class Orbiter extends Spacecraft {
      double altitude;
      Orbiter(String name, DateTime launchDate, this.altitude)
          : super(name, launchDate);
    }

    Read more about extending classes, the optional @override annotation, and more.

     

    Mixins

    Mixins are a way of reusing code in multiple class hierarchies. The following class can act as a mixin:

    Mixin은 여러 class hierarchies를 재사용하는 방법입니다. 다음 class는 mixin으로 활용될 수 있습니다.

    class Piloted {
      int astronauts = 1;
      void describeCrew() {
        print('Number of astronauts: $astronauts');
      }
    }

    To add a mixin’s capabilities to a class, just extend the class with the mixin.

    class PilotedCraft extends Spacecraft with Piloted {
      // ···
    }
    

    PilotedCraft now has the astronauts field as well as the describeCrew() method.

    Read more about mixins.

    Interfaces and abstract classes

    Dart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.

    class MockSpaceship implements Spacecraft {
      // ···
    }

    Read more about implicit interfaces.

    You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).

    abstract class Describable {
      void describe();
    
      void describeWithEmphasis() {
        print('=========');
        describe();
        print('=========');
      }
    }

    Any class extending Describable has the describeWithEmphasis() method, which calls the extender’s implementation of describe().

    Read more about abstract classes and methods.

    Async

    Avoid callback hell and make your code much more readable by using async and await.

    callback 지옥을 피해 당신의 코드를 좀 더 읽기 쉽도록 async 와 await를 사용하세요.

    const oneSecond = Duration(seconds: 1);
    // ···
    Future<void> printWithDelay(String message) async {
      await Future.delayed(oneSecond);
      print(message);
    }
    

    The method above is equivalent to:

    위의 method는 아래와 같습니다.

    Future<void> printWithDelay(String message) {
      return Future.delayed(oneSecond).then((_) {
        print(message);
      });
    }

    As the next example shows, async and await help make asynchronous code easy to read.:

    다음 예제가 async 와 await가 비동기 코드를 읽기 쉽게 만들어준다는 것을 보여줍니다.

    Future<void> createDescriptions(Iterable<String> objects) async {
      for (var object in objects) {
        try {
          var file = File('$object.txt');
          if (await file.exists()) {
            var modified = await file.lastModified();
            print(
                'File for $object already exists. It was modified on $modified.');
            continue;
          }
          await file.create();
          await file.writeAsString('Start describing $object in this file.');
        } on IOException catch (e) {
          print('Cannot create description for $object: $e');
        }
      }
    }

    You can also use async*, which gives you a nice, readable way to build streams.

    또한 async를 사용해서 읽기 쉽게 build stream을 작성할 수 있습니다.

    Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
      for (var object in objects) {
        await Future.delayed(oneSecond);
        yield '${craft.name} flies by $object';
      }
    }

    Read more about asynchrony support, including async functions, Future, Stream, and the asynchronous loop (await for).

    Exceptions

    To raise an exception, use throw:

    예외를 대비해서 throw를 사용하세요

    if (astronauts == 0) {
      throw StateError('No astronauts.');
    }

    To catch an exception, use a try statement with on or catch (or both):

    예외를 잡으려면 on이나 catch와 함께(혹은 둘 다) try statement를 사용하세요.

    try {
      for (var object in flybyObjects) {
        var description = await File('$object.txt').readAsString();
        print(description);
      }
    } on IOException catch (e) {
      print('Could not describe object: $e');
    } finally {
      flybyObjects.clear();
    }

    Note that the code above is asynchronous; try works for both synchronous code and code in an async function.

    위의 비동기 코드입니다. try는 동기와 비동기 모두에서 작동합니다.

    Read more about exceptions, including stack traces, rethrow, and the difference between Error and Exception.

    Other topics

    Many more code samples are in the language tour and the library tour. Also see the Dart API reference, which often contains examples.

    더 많은 코드 샘플이 language tour 와 library tour에 있습니다. 더 많은 예제도 담긴 Dart API reference도 참고하세요.

    반응형

    댓글

Designed by Tistory.