달력

9

« 2024/9 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

'Android'에 해당되는 글 4

  1. 2019.05.18 Flutter 페이지 이동(navigation)
  2. 2019.05.14 Flutter sqlite 연동하기
  3. 2019.04.22 Flutter Future 설명
  4. 2018.05.07 Framework7 시작
2019. 5. 18. 09:45

Flutter 페이지 이동(navigation) Android2019. 5. 18. 09:45

1. 페이지 이동

Widget build(BuildContext context){
	... 코드 ...
	
	onTab: _showOtherPage,
	
	... 코드 ...
}

_showOtherPage(){
	// Navigator.of(context)로 현재 context의 navigator에 접근한다
	// 새 route를 stack에 push하거나 pop할 수 있다
	Navigator.of(context).push(
		MaterialPageRoute(
			// builder 메서드는 항상 context를 취한다
			builder: (context){
				return otherPage();
			}
		),
	);
}


=> Flutter에서 자동으로 Appbar에 뒤로가기 버튼을 leading으로 추가해 준다


2. 페이지 이동 + 리턴값 받기

Widget build(BuildContext context){
	... 코드 ...
	
	onTab: _showOtherPage,
	
	... 코드 ...
}

_showOtherPage(){
	// Navigator.of(context)로 현재 context의 navigator에 접근한다
	// 새 route를 stack에 push하거나 pop할 수 있다
	TestClass newTestObject = await Navigator.of(context).push(
		MaterialPageRoute(
			// builder 메서드는 항상 context를 취한다
			builder: (context){
				return otherPage();
			}
		),
	);
	
	if(newTestObject != null){	
		... 코드 ...
	}
}

'Android' 카테고리의 다른 글

Flutter sqlite 연동하기  (0) 2019.05.14
Flutter Future 설명  (0) 2019.04.22
Framework7 시작  (0) 2018.05.07
:
Posted by SK
2019. 5. 14. 20:34

Flutter sqlite 연동하기 Android2019. 5. 14. 20:34

https://flutter.dev/docs/cookbook/persistence/sqlite 를 참조하여 작성

1. 모델생성

class ExampleVo { 
  final int id; 
  final String contents; 

  ExampleVo({this.id, this.contents}); 

  // key 부분은 database의 컬럼명이 들어가야 한다 
  Map<String, dynamic> toMap(){ 
    return { 
      'id':id, 
      'contents':contents 
    } 
  } 
} 



2. pubspec.yaml에 패키지 의존성 추가

// sqlite가 아니라 sqflite임에 주의 
dependencides: 
  flutter: 
    sdk: flutter 
  sqflite: any 
  path: any 


3. database 연결 및 테이블 생성

final Future database = openDatabase( 
  // join function을 이용하여 각 platform마다 올바르게 경로를 확인 
  path: join(await getDatabasePath(), 'example_database.db'), 
   
  // onCreate function을 실행하기 위한 version 설정 
  version: 1, 
   
  // create table 구문 실행 
  onCreate: (db, version) { 
    return db.execute( 
      "create table example(id integer, contets text)", 
    ); 
  }, 
); 



4. crud 구현

// create 
Future insertExample (ExampleVo e) async{ 
  final Database db = await database; 
  await db.rawInsert( 
    'insert into example (id, contents) values (?,?)', 
    [${e.id}, ${e.contents}] 
  ); 
  /* 
    await db.insert('example',e.toMap()); 
  */ 
} 
// retreive 
Future selectExample (ExampleVo e) async{ 
  final Database db = await database; 
  return List<Map<String,dynamic>> exampleList  
    = await db.rawQuery('select * from example'); 
  /*  
    return List<Map<String,dynamic>> exampleList  
      = await db.query('example', columns:[id,contents]); 
  */ 
   
  // 추출된 map은 read-only이기 때문에 수정이 필요할 경우 아래와 같이  
  /* 
    Map<String, dynamic> e = mapList.first; 
    return List.generate(mapList.length, (idx) => { 
                return ExampleVo( 
                  id = mapList[idx]['id']; 
                  contents = mapList[idx]['contents']; 
                ); 
              }); 
     
  */ 
} 
// update 
Future updateExample (ExampleVo e) async{ 
  final Database db = await database; 
  await db.rawUpdate( 
    'update example set contents=? where id=?', 
    [${e.contents},${e.id}]; 
  ); 
  /* 
    await db.update('example',e.toMap(), where: 'id=?', whereArgs: [e.id]); 
  */ 
} 
// delete 
Future deleteExample (ExampleVo e) async{ 
  final Database db = await database; 
  await db.rawDelete( 
    'delete from example where id = ?', 
    [${e.id}] 
  ); 
  /* 
    await db.delete('example',where: id=?', whereArgs: [e.id]); 
  */ 
} 

/* 

  final e1 = ExampleVo (id: 0, contents: 'example0'); 
  await insertExample(e1); 
   
  print(await selectExample()): 
   
  final e2 = ExampleVo (id: 0, contents: 'example1'); 
  await updateExample(e2); 
   
  print(await selectExample()): 
   
  await deleteExample(e2); 
   
  print(await selectExample()): 

*/

'Android' 카테고리의 다른 글

Flutter 페이지 이동(navigation)  (0) 2019.05.18
Flutter Future 설명  (0) 2019.04.22
Framework7 시작  (0) 2018.05.07
:
Posted by SK
2019. 4. 22. 22:47

Flutter Future 설명 Android2019. 4. 22. 22:47

flutter에서 db에 저장할 때나 http 요청 등에 많이 쓰이는 Future에 대해 간략히 정리한다.


Future, async, await


flutter의 Future는 javascript의 promise와 유사하다. 미래의 어느 시점에 사용간으한 value를 표현하기 위해 사용한다.

http package에서 get, post 등의 method를 통해 받는 response라든가 new Future 생상자를 통해서 Future Object를 얻을 수 있다.

Future에 관한 대략적인 정보는 아래와 같다.


- Future Object의 상태

pending: 프로세스가 진행중

complete: 프로세스 완료, 세부적으로 complete with value와 complete with error로 분류된다

- Future.then  * try

Future가 complete 되었을 때 callback을 추가하기 위해 사용되는 method다

var future = ... return future object ...

future.then((value){

print('success');

}, onError: (error){

print('error');

}

});


- Future.catchError  * catch

future.then의 onError는 해당 Future 의 error만 처리한다. future가 체이닝되어 발생할 때 한번에 잡기 위해서는 catchError를 사용해야 한다.

new Future.value(1).then(v)({

return Future.error('error');

}).then((v){

return Future.value(v);

})catchError((error){

print('error');

});


- Future.whenCompelete  * finally

var future = ... return future object ...

future.then(print).catchError(print).whenCompelete((){

print('done');

});

- Future.timeout

timeout에서 설정한 시간이 지난 후에 TimeoutException을 발생시킨다

future.delayed(Duration(seconds: 5), (){

return '1';

}).timeout(Duration(seconds: 2)).then(print).catchError(print);

또는 시간이 지난 후 기본값 리턴

future.delayed(Duration(seconds: 5), (){

return '1';

}).timeout(Duration(seconds: 2), onTimeout:(){

return 'default value';

}).then(print).catchError(print);

- async, await

Future가 chain을 이룰 경우 코드가 더러워지기 때문에 async와 await을 사용한다.

Future를 동기처리 코드처럼 사용하게 된다.

void main() async {

var future = Future.delayed(Duration(seconds: 3), () => {return 1});

// await은 Future의 결과를 기다린다

var rslt = await future;

print(rslt);  // rslt 는 1

}

async, await 사용시 error 처리는 try ~ catch ~ finally 구문을 사용한다.

void main() async {

var future = Future.delayed(Duration(seconds: 3), () => {return Future.error('error')});

try{

var rslt = await future;

print(rslt);

}catch(e){

print(e);

}finally{

print('done');

}

}

Future 체이닝이 이루어지는 경우 async, await을 사용하면 callback hell을 방지할 수 있다.

void main() async{

var f1 = (int value) async => v+1;

var f2 = (int value) async => v+2;

var f3 = (int value) async => v+3;

var value=100;

value = await f1(value);

value = await f2(value);

value = await f3(value);

print(value);

}

** 참고: https://flutter-academy.com/async-in-flutter-futures/

'Android' 카테고리의 다른 글

Flutter 페이지 이동(navigation)  (0) 2019.05.18
Flutter sqlite 연동하기  (0) 2019.05.14
Framework7 시작  (0) 2018.05.07
:
Posted by SK
2018. 5. 7. 12:06

Framework7 시작 Android2018. 5. 7. 12:06

안드로이드 앱 개발을 하려다 보니, 네이티브를 배우기 너무 귀찮다. 안그래도 할 것도 많고.

웹개발은 어느정도 지식이 있으니 Phonegap을 이용해서 개발하자 싶었는데, 이것도 은근히 할게 많다.(디자인이라든지...)

관련해서 프레임워크, 부트스트랩 류의 것들이 뭐가 있나 찾아보다가 Framework7라는 녀석을 알게됐다. 

jQuery와 비슷한 문법으로 DOM 이벤트 처리도 가능하고, Ionic이나 다른 것보다 이리저리 다른 것들에 비해서 편해보인다(학습 곡선이 낮아보인다). 

일단 이녀석을 가지고 해보기로 결정.

그런데 튜토리얼이 꽤 부실하고 커뮤니티가 잘 안되어 있어서 걱정도 된다. 

https://framework7.io/ 


'Android' 카테고리의 다른 글

Flutter 페이지 이동(navigation)  (0) 2019.05.18
Flutter sqlite 연동하기  (0) 2019.05.14
Flutter Future 설명  (0) 2019.04.22
:
Posted by SK