Ferry를 사용하여 GraphiQL 간편한 응용 프로그램 만들기

18071 단어 FlutterGraphQLtech

프로젝트 작성


공식 문서에 따라 설정
https://ferrygraphql.com/docs/setup/
ghq create gqlflutter
flutter create .

패키지 설치


flutter pub add gql_http_link
flutter pub add ferry_flutter # 追加
flutter pub add -d ferry_generator
flutter pub add -d build_runner

다운로드 모드 파일


참고 자료
https://ferrygraphql.com/docs/codegen

설치 모드 다운로드 도구


npm install -g get-graphql-schema

다운로드 모드


이번에는 포켓몬 그래피큐어 APIhttps://graphql-pokemon2.vercel.app를 활용했다.감사합니다.
get-graphql-schema https://graphql-pokemon2.vercel.app > lib/schema.graphql

코드를 쓰다


GraphiQL 쿼리 준비


포켓몬 데이터 가져오기 검색 쓰기
# lib/graphql/all_pokemon.graphql
query AllPokemon($first: Int!) {
  pokemons(first: $first) {
    id
    name
    maxHP
    image
  }
}

build.만들기


프로젝트 경로에 yaml 저장
https://ferrygraphql.com/docs/codegen#build-generated-classes
# build.yaml
targets:
  $default:
    builders:
      gql_build|schema_builder:
        enabled: true
      gql_build|ast_builder:
        enabled: true
      gql_build|data_builder:
        enabled: true
        options:
          schema: your_package_name|lib/schema.graphql
      gql_build|var_builder:
        enabled: true
        options:
          schema: your_package_name|lib/schema.graphql
      gql_build|serializer_builder:
        enabled: true
        options:
          schema: your_package_name|lib/schema.graphql

      ferry_generator|req_builder:
        enabled: true
        options:
          schema: your_package_name|lib/schema.graphql

GraphiQL 조회에서 데이터 코드 생성


flutter pub run build_runner build
lib/graphiql은 다음과 같다.
all_pokemon.data.gql.dart
all_pokemon.data.gql.g.dart
all_pokemon.graphql
all_pokemon.req.gql.dart
all_pokemon.var.gql.dart

GraphiQL client 준비


GraphiQL Celient를 얻을 수 있는 방법을 준비합니다.
class MyHomePage extends StatefulWidget {
  // ...
  
  Client? _client;  
  
  Client get client {
    if (_client == null) {
      final link = HttpLink('https://graphql-pokemon2.vercel.app');
      return _client = Client(link: link);
    } else {
      return _client!; // NOTE: ! 消せないの?
    }
  }
  // ...
}

포켓몬 목록 보이기


ferryferry_flutter는 flutter에서 사용하기 편리하도록 Widget을 준비했다.
Operation widget을 사용하면 좋은 느낌으로 데이터를 얻을 수 있습니다.
class MyHomePage extends StatefulWidget {
  // ...
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Operation(
        client: client,
        operationRequest: GAllPokemonReq((b) => b..vars.first = 151),
        builder: (BuildContext context,
            OperationResponse<GAllPokemonData, GAllPokemonVars>? response,
            Object? error) {
          if (response == null || response.loading) {
            return const Center(child: CircularProgressIndicator());
          }

          final pokemons = response.data?.pokemons ?? BuiltList();

          return ListView.builder(
              itemCount: pokemons.length,
              itemBuilder: (context, index) {
                final pokemon = pokemons[index];

                return Card(
                  child: Row(children: <Widget>[
                    SizedBox(
                      child: Image.network(
                          pokemon.image ?? 'https://placehold.jp/150x150.png'),
                      width: 100,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Name: ${pokemon.name ?? '[unknown]'}'),
                          Text(
                            'MAX HP: ${pokemon.maxHP}',
                            textAlign: TextAlign.left,
                          ),
                        ],
                      ),
                    )
                  ]),
                );
              });
        },
      ),
    );

완성


이런 느낌으로 포켓몬 일람이 나오면 완성이 됩니다.
完成画面

좋은 웹페이지 즐겨찾기