Flutter
GraphQL
Flutter GraphQL로 오프라인 우선 데이터베이스 구현
10 분
오프라인 우선 데이터베이스를 graphql api를 사용하여 구현하기 소개 여기 계신다면, 나머지 튜토리얼을 통해 graphql 쿼리 및 변형을 실행하여 데이터를 가져오고 수정하는 방법에 익숙하실 것입니다 이 문서에서는 flutter와 graphql을 사용하여 오프라인 우선 사용자 인터페이스를 구현하는 방법을 탐구할 것입니다 목표 flutter graphql 오프라인 클라이언트의 내부 아키텍처 이해하기 애플리케이션이 오프라인 상태에서도 graphql 쿼리를 실행할 수 있도록 허용하기 오프라인 데이터 지속성 구현하기 전제 조건 사용자가 dart와 flutter에 대한 기본적인 이해가 필요합니다 필수는 아니지만, graphql 요리책이 일부 graphql 개념 을 이해하는 데 유용할 것입니다 다음의 필수 주제를 완료해야 합니다 flutter graphql 설정 및 이전 코드 설정과 back4app 백엔드 구현이 필요합니다 1 오프라인 캐시 설정하기 flutter graphql 클라이언트는 기본적으로 “오프라인 쿼리”를 지원합니다 즉, 오프라인 상태에서 graphql 데이터를 쿼리할 때 오류를 발생시키지 않으며 캐시에서 데이터를 가져옵니다 우리는 이것이 앱 세션 간에 캐시를 지속하는 것과 다르다는 점을 주목해야 합니다 특히 flutter graphql 클라이언트는 디스크에 캐시 지속성을 가지고 있지 않습니다 따라서 앱이 시스템 트레이에서 닫히고 다시 열리면 데이터는 여전히 가져와야 합니다 동일한 기능을 활성화하려면 오프라인 캐시를 활성화해야 합니다 이동하십시오 main dart 1 return materialapp( 2 home graphqlprovider( 3 child cacheprovider( // cache provider widget that provides the offline queries support 4 child myhomepage(), 5 ), 6 client client, 7 ), 8 ); 2 저장된 환경 설정 설정하기 flutter graphql 클라이언트를 사용할 때의 한 가지 주의사항은 애플리케이션이 닫힐 때 자체 캐시를 저장하지 않으며, 애플리케이션이 다시 열릴 때 캐시를 복원하지 않는다는 것입니다 동일한 기능을 구현하기 위해 flutter shared preferences 라이브러리를 활용할 것입니다 이 라이브러리는 간단한 데이터에 대한 플랫폼별 지속 저장소를 래핑합니다 (ios 및 macos의 nsuserdefaults, android의 sharedpreferences 등), 본질적으로 매우 간단한 방식으로 오프라인에서 데이터를 저장할 수 있게 해줍니다 라이브러리를 설치하려면 pubspec yml https //github com/templates back4app/flutter graphql/blob/772c058c74d870798af1cce7a29a5046f9dda456/pubspec yaml#l34 파일에 추가하십시오 다음 내용을 main dart 에 추가하세요 1 import 'package\ shared preferences/shared preferences dart'; 2 3 class sharedpreferenceshelper { 4 static final string offline cache key = 'programminglanguagelistresponse'; 5 6 static future\<programminglanguagelist> getcache() async { 7 final sharedpreferences prefs = await sharedpreferences getinstance(); 8 final cache = prefs getstring( offline cache key); 9 final offlinedata = 10 cache != null ? programminglanguagelistfromjson(cache) null; 11 12 return offlinedata; 13 } 14 15 static future\<bool> setcache(dynamic value) async { 16 final sharedpreferences prefs = await sharedpreferences getinstance(); 17 18 return prefs setstring( offline cache key, jsonencode(value)); 19 } 20 } shared preferences 라이브러리는 데이터를 키 값 형태로 저장하며, 값은 json 문자열로 변환됩니다 이 데이터를 우리의 데이터 모델로 파싱해야 합니다 3 로컬에 저장된 데이터 파싱하기 우리는 programing languages model dart programing languages model dart 라는 새로운 파일을 만들 것입니다 이 파일은 파싱 로직을 저장합니다 우리는 https //app quicktype io/ https //app quicktype io/ 에서 json을 다트 모델로 변환하는 도구에 우리의 graphql 응답을 붙여넣어 이 로직을 생성할 것입니다 생성된 코드를 복사하여 파일을 생성할 것입니다 programing languages model dart programing languages model dart https //github com/templates back4app/flutter graphql/blob/flutter graphql offline/lib/programing languages model dart https //github com/templates back4app/flutter graphql/blob/flutter graphql offline/lib/programing languages model dart 4 오프라인 저장소 논리 통합 데이터가 존재하지 않으면 공유 환경 설정에서 데이터를 사용할 것입니다 데이터가 공유 환경 설정에도 없다면 단순히 로딩 아이콘을 표시할 것입니다 이제 모든 변경 사항을 통합하기 위해 myhomepagestate myhomepagestate 의 빌드 메서드에서 변경 사항을 구현할 것입니다 우리는 futurebuilder futurebuilder 위젯을 사용하여 sharedpreferenceshelper 클래스에서 데이터를 소비할 것입니다 1 return futurebuilder\<programminglanguagelist>( 2 future sharedpreferenceshelper getcache(), 3 builder (prefs, snapshot) { 4 final offlinedata = snapshot data; 5 if (!snapshot haserror) { 6 return safearea( 7 … futurebuilder 위젯을 사용하면 상태를 사용하지 않고도 코드를 작성할 수 있습니다 공유된 기본 설정에서 데이터를 가져오는 과정은 비교적 빠릅니다 공유된 기본 설정을 초기화하고 오프라인 저장소에서 데이터를 가져오는 동안 로더를 표시할 수도 있습니다 이제 이 오프라인 데이터 객체를 사용하여 graphql에서 데이터가 사용 가능하지 않을 때 렌더링합니다 코드를 조금 리팩토링할 것입니다 다음은 쿼리 쿼리 https //github com/templates back4app/flutter graphql/blob/flutter graphql offline/lib/main dart 위젯에 대한 코드가 될 것입니다 1 body query( 2 options queryoptions( 3 documentnode gql(query), 4 ), 5 builder ( 6 queryresult result, { 7 refetch refetch, 8 fetchmore fetchmore, 9 }) { 10 final data = result data == null 11 ? offlinedata 12 programminglanguagelistfromjson( 13 jsonencode(result data)); 14 if (data == null) { 15 return center( 16 child text( 17 "loading ", 18 style textstyle(fontsize 20 0), 19 )); 20 } else { 21 sharedpreferenceshelper setcache(data); 22 return listview\ builder( 23 itembuilder (buildcontext context, int index) { 24 if (index == 0) { 25 return center( 26 child raisedbutton( 27 onpressed refetch, 28 child result loading == true 29 ? text("loading ") 30 text("refetch"), 31 ), 32 ); 33 } 34 return listtile( 35 title text(data programminglanguages 36 edges\[index 1] node name), 37 trailing text(data programminglanguages 38 edges\[index 1] node stronglytyped 39 ? "strongly typed" 40 "weekly typed"), 41 ); 42 }, 43 itemcount data programminglanguages edges length + 1, 44 ); 45 } 46 }, 47 ), 48 ), 다음과 같은 결과를 얻어야 합니다 결론 이제 우리는 데이터를 오프라인으로 저장하고 애플리케이션이 인터넷에 연결될 때 데이터를 재검증함으로써 매우 좋은 모바일 경험을 보장할 수 있습니다 또한 사용자 경험을 향상시키는 중요한 측면 중 하나는 flutter graphql 클라이언트가 이전 응답을 캐시하고 새로운 요청을 자동으로 전송한다는 것입니다 이로 인해 데이터를 다시 가져오는 동안 번거로운 로딩 화면을 계속 보여줄 필요가 없습니다 이 기사의 코드는 다음에서 확인할 수 있습니다 https //github com/templates back4app/flutter graphql/tree/flutter graphql offline https //github com/templates back4app/flutter graphql/tree/flutter graphql offline