---
title: 플러터에서 GraphQL 클라이언트 정밀 설정 및 접속 가이드
slug: docs-kr/flutter/graphql/flutter-graphql-setup
description: Flutter로 GraphQL 클라이언트를 설정하고 Back4app 서버에 연결하는 방법을 기술적으로 설명합니다.
image: https://www.back4app.com/images/logo-social.png
createdAt: 2024-03-18T17:59:04.725Z
---

# 플러터 GraphQL 설정



## 소개

지난 튜토리얼에서는 Flutter와 함께 Back4app GraphQL을 사용하는 이점을 이해했습니다. 이 기사에서는 프로젝트의 기본 구조를 설정하고 Back4app 서버에 연결할 것입니다.

## 목표

- **플러터 환경 설정**
- **플러터 GraphQL 설정 해부**
- **플러터 GraphQL 연결**
- **플러터 GraphQL 연결 재사용 및 패턴**

## 전제 조건

:::hint{type="info"}
- 사용자가 Dart와 Flutter에 대한 기본적인 이해를 가지고 있어야 합니다;
- 필수는 아니지만, GraphQL 요리책이 [GraphQL 개념](https://www.back4app.com/docs/parse-graphql/graphql-getting-started)을 이해하는 데 유용할 것입니다.
:::

## 0 - Back4app 허브에서 앱 설정

앱을 생성해야 합니다. 문서에서 다음을 따를 수 있습니다: [https://www.back4app.com/docs/get-started/new-parse-app](https://www.back4app.com/docs/get-started/new-parse-app)

이 튜토리얼을 위해 필요한 클래스를 설정하기 위해 Back4app 허브를 사용할 것입니다.
다음으로 가십시오: [https://www.back4app.com/database/chinmay/flutter-graphql](https://www.back4app.com/database/chinmay/flutter-graphql). API에 연결을 클릭하십시오.

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/BPEg6W5LOVp_grHWrF541_image.png)

새로 생성된 앱을 선택한 다음 완료입니다!

## 1 - Flutter 설정하기

Flutter 설정은 비교적 간단합니다. 우리는 [공식 Flutter 웹사이트](https://flutter.dev/docs/get-started/install)의 설정 지침을 따를 것입니다.
이후 우리는 다음 명령어를 사용하여 간단한 Flutter 애플리케이션을 만들 것입니다:

:::BlockQuote
flutter create flutter\_graphql\_setup
:::

명령어 <font color="#2166ae">`flutter doctor`</font>를 사용하여 모든 것이 정상인지 확인하세요. 애플리케이션을 실행합니다:

:::BlockQuote
cd flutter\_graphql\_setup&#x20;
flutter run
:::

## 2 - Flutter GraphQL 라이브러리 설치하기

이 클라이언트를 구현하기 위해 첫 번째 기사에서 언급한 flutter\_graphql 라이브러리를 사용할 것입니다.
이제 이 라이브러리를 패키지에 추가하겠습니다 <font color="#2166ae">`pubspec.yaml`</font>.

:::BlockQuote
dependencies:
graphql\_flutter: ^3.0.0
:::

## 3 - Flutter GraphQL 공급자 만들기

GraphQL에서는 여러 엔드포인트와 작업할 필요가 없으며, 요청 데이터를 쿼리하는 데 사용되는 단일 엔드포인트만 있습니다. 그리고 우리는 그 엔드포인트에 GraphQL 쿼리를 보냅니다. 일반적으로 우리가 하는 일은 적절한 헤더를 보내고 쿼리를 필요에 맞게 형식화하는 클라이언트의 인스턴스를 만드는 것입니다.
우리는 클라이언트를 만들 것이며, 이를 위해 링크(HttpLink 클래스의 인스턴스)와 캐시 저장소가 필요합니다. 우리는 <font color="#2166ae">`HttpLink`</font>을 링크로 사용하고 OptimisticCache를 캐싱에 사용할 것입니다. 코드는 다음과 같이 작성됩니다:

다음은 [main.dart](https://github.com/templates-back4app/Flutter-GraphQL/blob/flutter-graphql-setup/lib/main.dart)에 작성할 내용입니다:

```dart
1   final HttpLink httpLink = HttpLink(
2         uri: 'https://parseapi.back4app.com/graphql',
3         headers: {
4           'X-Parse-Application-Id': kParseApplicationId,
5           'X-Parse-Client-Key': kParseClientKey,
6         }, //getheaders()
7       );
8
9       ValueNotifier<GraphQLClient> client = ValueNotifier(
10        GraphQLClient(
11          cache: OptimisticCache(dataIdFromObject: typenameDataIdFromObject),
12          link: httpLink,
13        ),
14      );
15
```

## 4 - GraphQL을 사용하여 Back4app에 연결하기

“API 콘솔” > “GraphQl 콘솔” 옵션에서 Back4app 대시보드로 이동합니다:

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/-xlGmAHlGt5Y-dUY_Zj3J_image.png)

기록해 두세요:

1. **API URL**
2. **Parse 앱 ID**
3. **Parse 클라이언트 ID**

우리는 [constants.dart](https://github.com/templates-back4app/Flutter-GraphQL/blob/flutter-graphql-setup/lib/constants.dart)라는 새 파일을 <font color="#2166ae">`lib`</font> 폴더에 생성할 것입니다.

:::BlockQuote
String kParseApplicationId= "";
String kParseClientKey = "";
:::

## 5 - 데이터 쿼리하기

우리의 컴포넌트는 GraphQLProvider 위젯으로 감싸질 것이며, 이는 위젯에 필요한 세부 정보를 제공할 것입니다.
우리는 2단계에서 생성한 클라이언트의 인스턴스를 제공해야 합니다.
우리는 GraphQL 콘솔을 사용하여 쿼리를 작성할 것입니다. GraphQL 쿼리에 대해 더 알고 싶다면 [GraphQL 요리책 섹션.](https://www.back4app.com/docs/parse-graphql/graphql-getting-started)

```graphql
1   import 'package:graphql_flutter/graphql_flutter.dart';
2   import 'constants.dart';
3
4   class _MyHomePageState extends State<MyHomePage> {
5     String name;
6     String saveFormat;
7     String objectId;
8
9     String query = '''
10    query FindLanguages{
11    languages{
12      count,
13      edges{
14        node{
15          name,
16          saveFormat
17        }
18      }
19    }
20  }
21    ''';
22
23    @override
24    Widget build(BuildContext context) {
25      return SafeArea(
26        child: Scaffold(
27          appBar: AppBar(
28            title: Text(
29              'Parsing data using GraphQL',
30            ),
31          ),
32          body: Query(
33            options: QueryOptions(
34              documentNode: gql(query),
35            ),
36            builder: (
37             QueryResult result, {
38              Refetch refetch,
39              FetchMore fetchMore,
40            }) {
41              if (result.data == null) { //check if data is loading
42                return Center(
43                    child: Text(
44                  "Loading...",
45                  style: TextStyle(fontSize: 20.0),
46                ));
47              }  
48               //to implement rendering logic
49            },
50          ),
51        ),
52      );
53    }
54  }
```

## 6 - 목록 렌더링

우리는 <font color="#2166ae">`ListView`</font> 위젯을 사용하여 목록을 렌더링할 것입니다, [main.dart](https://github.com/templates-back4app/Flutter-GraphQL/blob/flutter-graphql-setup/lib/main.dart)

```dart
1   else {
2                 return ListView.builder(
3                   itemBuilder: (BuildContext context, int index) {
4                     return ListTile(
5                       title: Text(result.data["programmingLanguages"]["edges"][index]["node"]['name']),
6                       trailing: Text(
7                         result.data["programmingLanguages"]["edges"][index]
8                           ["node"]['stronglyTyped'] ? "Strongly Typed":"Weekly Typed"
9                       ),
10                    );
11                  },
12                  itemCount: result.data["programmingLanguages"]["edges"].length,
13                );
14              }
15            
```

우리는 화면에서 다음을 얻어야 합니다:

::Image[]{src="https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/6T_PJltnmJwKxobbbkw2Q_image.png" size="50" width="396" height="673" position="center" showCaption="false"}

## 결론

우리는 Flutter GraphQL 클라이언트를 구성하고 Back4app GraphQL API에 연결했습니다.
같은 코드 찾으실 수 있습니다: [https://github.com/templates-back4app/Flutter-GraphQL/tree/flutter-graphql-setup.](https://github.com/templates-back4app/Flutter-GraphQL/tree/flutter-graphql-setup)
