Flutter & Dart 문법 좀 보면서 끄적끄적 정리해봅니다.
기초문법
- Optional 매개변수 사용 2가지
positional Parameter – 항상 Default 값
getHttpUrl(String server, String path, [int port=80]) {} - named Parameter
– (String name, {int age})함수정의에서 {}로 감싸서 선택적으로 사용
named Parameter 쓸때는 무조건 함수호출할때 이름 넣어줘야한다.
2개 파라미터 같이 쓸수 없음. - 익명함수
(number) {
return number % 2 === 0;
}; - 정적 Method
static int isValue(int param) {
} - 문장 출력
– ”’ 멀티
용 ”’ - 변수타입 변경
변수타입이 후에 변경된다면 dynamic 사용
dynamic name = “이름”
List<dynamic> list = [1,2, “이름”]; - Runtime시 오브젝트 type 확인
object.runtimeType
returns the type of object
final aListOfStrings = [‘one’, ‘two’, ‘three’] – JSArray<String>
final aSetOfStrings = {‘one’, ‘two’, ‘three’} – _LinkedHashSet<String> [add/remove/contains]
final aMapOfStringsToInts = { ‘one’: 1, ‘two’: 2, ‘three’: 3,} – JsLinkedHashMap<String, int> - 스프레드연산 (…)
list 내역들을 뿌려주는 역할
var numbering = [1,2,3]
[…numbering, 4,5] - Cascades 사용 (계단식)
myObject
..someMethod() - Class 접근 지정자
변수이름 앞에 _ 기호를 붙이면 외부에서 접근불가, 안붙이면 외부에서 접근가능 - get / set
class MyClass {
int _aProperty = 0;
int get aProperty => _aProperty;
set aProperty(int value) {
if (value >= 0) {
_aProperty = value;
}
}
}
null 확인 ?.
dart:core library (link)
Iterable 정리
Iterable Class는 List, Set 가 있고 시퀀스하게 접근가능
final aListOfStrings = ['one', 'two', 'three']; final aSetOfStrings = {'one', 'two', 'three'}; final aMapOfStringsToInts = { 'one': 1, 'two': 2, 'three': 3, }; 아래처럼 지정해도됨. final aListOfInts = <int>[]; final aSetOfInts = <int>{}; final aMapOfIntToDouble = <int, double>{};
– Iterable<int> iterable = [1, 2, 3];
iterable.elementAt(1); iterable.first; iterable.last;
: Using any() and every()
iterable.firstWhere(); 식표현 사용방법 3가지
bool predicate(String element) { return element.length > 5; } main() { var items = ['Salad', 'Popcorn', 'Toast', 'Lasagne']; // You can find with a simple expression: var element1 = items.firstWhere((element) => element.length > 5); print(element1); // Or try using a function block: var element2 = items.firstWhere((element) { return element.length > 5; }); print(element2); // Or even pass in a function reference: var element3 = items.firstWhere(predicate); print(element3); // You can also use an `orElse` function in case no value is found! var element4 = items.firstWhere( (element) => element.length > 10, orElse: () => 'None!', ); print(element4); }
As an expression : 람다식
As a block: 함수에 return식
As a function : 안에 orElse 추가
Example: Using any() and every()
any()
: 하나의 element를 만족하면 Return trueevery()
: 모두 만족하면 Return true
if (items.any((element) => element.contains(‘Z’))) { }
Filtering Example: Using where()singleWhere()
or firstWhere()
, where()
값 만족 못하면 empty값 들어옴.
Filtering Example: Using takeWhiletakeWhile()
: 조건 만족전까지만 출력 (until)skipWhile()
: 조건 만족한거부터 출력 (after)
Mapping
PUB 라이브러리
- pub get (link) : 외부 라이브러리를 추가한후 다운
- pub upgrade (link) : 외부라이브러리 업그레이드
- pub outdated (link): 2.8 이후 추가 최신 다운
- 그밖에 리스트 (link)
CLI : – $ flutter / dart + pub outdated [options]
pub get 에서 받는거 쌓이는 디렉토리 /.pub-cache
. 윈도우 %LOCALAPPDATA%\Pub\Cache
패캐지 사이트
- https://pub.dev/
테스트 실행환경
- https://dartpad.dev/?
Sample Code
기본 구조는 다음에 올려야겠다..
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, // This makes the visual density adapt to the platform that you run // the app on. For desktop platforms, the controls will be smaller and // closer together (more dense) than on mobile platforms. visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter TEST Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }