인프런 커뮤니티 질문&답변

강의 수집가님의 프로필 이미지
강의 수집가

작성한 질문수

[코드팩토리] [중급] Flutter 진짜 실전! 상태관리, 캐시관리, Code Generation, GoRouter, 인증로직 등 중수가 되기 위한 필수 스킬들!

일반 Navigation에서 GoRouter로 전환하기

gorouter 7 버전 상세화면 이동 오류

작성

·

677

2

안녕하세요

강의 실습 중 오류가 발생해서 도움을 요청드립니다

현재 개발 중인 환경은 윈도우에서 안드로이드 시뮬레이터로 진행 중이며 IDE 는 인텔리제이를 사용하고 있고 gorouter 7.0.1 버전을 사용해서 실습을 하고 있습니다

GoRouter 설정 부분은 7.0.1 버전 실습 강좌를 참고해서 변경했고 정상적으로 로그인 및 스플래시 스크린까지 동작을 했습니다.

레스토랑 리스트에서 레스토랑 상세화면으로 이동하는 부분을 실습 중 오류가 발생합니다

첫번째. context에서 gorouter 관련 메소드가 자동완성이 안되며 실제로 동작도 하지 않습니다.

두번째. context.named() ,context.go() 둘 다 아래와 같은 오류가 나타납니다

 

 

  1. 레스토랑 스크린

import 'package:actual/common/component/pagination_list_view.dart';
import 'package:actual/restaurant/component/restaurant_card.dart';
import 'package:actual/restaurant/provider/restaurant_provider.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; // 미사로 나옵니다

class RestaurantScreen extends StatelessWidget {
  const RestaurantScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PaginationListView(
      provider: restaurantProvider,
      itemBuilder: <RestaurantModel>(context, index, model) {
        return GestureDetector(
          onTap: () {
            context.go("/restaurant/${model.id}");
          },
          child: RestaurantCard.fromModel(model: model),
        );
      },
    );
  }
}

 

  1. 레스토랑 디테일 스크린

    import 'package:actual/common/layout/default_layout.dart';
    import 'package:actual/common/model/cursor_pagination_model.dart';
    import 'package:actual/common/utils/pagination_utils.dart';
    import 'package:actual/product/componet/product_card.dart';
    import 'package:actual/rating/component/rating_card.dart';
    import 'package:actual/rating/model/rating_model.dart';
    import 'package:actual/restaurant/component/restaurant_card.dart';
    import 'package:actual/restaurant/model/restaurant_detail_model.dart';
    import 'package:actual/restaurant/model/restaurant_model.dart';
    import 'package:actual/restaurant/provider/restaurant_provider.dart';
    import 'package:actual/restaurant/provider/restaurant_rating_provider.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    import 'package:skeletons/skeletons.dart';
    
    class RestaurantDetailScreen extends ConsumerStatefulWidget {
      static String get routeName => "restaurantDetail";
      final String id;
    
      const RestaurantDetailScreen({required this.id, Key? key}) : super(key: key);
    
      @override
      ConsumerState<RestaurantDetailScreen> createState() =>
          _RestaurantDetailScreenState();
    }
    
    class _RestaurantDetailScreenState
        extends ConsumerState<RestaurantDetailScreen> {
      final ScrollController controller = ScrollController();
      
      @override
      void initState() {
        super.initState();
        ref.read(restaurantProvider.notifier).getDetail(id: widget.id);
        controller.addListener(listener);
      }
      
      void listener(){
        PaginationUtils.paginate(controller: controller, provider: ref.read(restaurantRatingProvider(widget.id).notifier));
      } 
      
      @override
      Widget build(BuildContext context) {
        final state = ref.watch(restaurantDetailProvider(widget.id));
        final ratingsState = ref.watch(restaurantRatingProvider(widget.id));
    
        print(ratingsState);
    
        if (state == null) {
          return DefaultLayout(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
    
        return DefaultLayout(
          title: "제목",
          child: CustomScrollView(
            controller: controller,
            slivers: [
              renderTop(
                model: state,
              ),
              if (state is! RestaurantDetailModel) renderLoading(),
              if (state is RestaurantDetailModel) renderLabel(),
              if (state is RestaurantDetailModel)
                renderProducts(products: state.products),
              if (ratingsState is CursorPagination<RatingModel>)
                renderRatings(
                  models: ratingsState.data,
                ),
            ],
          ),
        );
      }
    
      SliverToBoxAdapter renderTop({
        required RestaurantModel model,
      }) {
        // 일반 위젯 넣기
        return SliverToBoxAdapter(
          child: RestaurantCard.fromModel(model: model, isDetail: true),
        );
      }
    
      SliverPadding renderRatings({
        required List<RatingModel> models,
      }) {
        return SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0),
         sliver: SliverList(
           delegate: SliverChildBuilderDelegate(
               (_, index) => Padding(
                 padding: const EdgeInsets.only(bottom: 16.0),
                 child: RatingCard.fromModel(
                   model: models[index],
                 ),
               ),
             childCount: models.length,
           ),
         ),
        );
      }
    
      SliverPadding renderLoading() {
        return SliverPadding(
          padding: EdgeInsets.symmetric(
            vertical: 16.0,
            horizontal: 16.0,
          ),
          sliver: SliverList(
            delegate: SliverChildListDelegate(
              List.generate(
                3,
                (index) => Padding(
                  padding: const EdgeInsets.only(bottom: 32.0),
                  child: SkeletonParagraph(
                    style: SkeletonParagraphStyle(
                      lines: 5,
                      padding: EdgeInsets.zero,
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      }
    
      SliverPadding renderLabel() {
        return SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.0),
          sliver: SliverToBoxAdapter(
            child: Text(
              "메뉴",
              style: TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
      }
    
      SliverPadding renderProducts({
        required List<RestaurantProductModel> products,
      }) {
        return SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.0),
          sliver: SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                final model = products[index];
    
                return Padding(
                  padding: const EdgeInsets.only(top: 16.0),
                  child: ProductCard.fromRestaurantProductModel(model: model),
                );
              },
              childCount: products.length,
            ),
          ),
        );
      }
    }

 

  1. 라우터 설정부분 (auth_provider.dart)

    List<GoRoute> get routes => [
          GoRoute(
            path: "/",
            name: RootTab.routeName,
            builder: (_, state) => RootTab(),
            routes: [
              GoRoute(
                path: "restaurant/:rid",
                name: RestaurantDetailScreen.routeName,
                builder: (_, state) => RestaurantDetailScreen(
                  id: state.pathParameters['rid']!,
                ),
              ),
            ],
          ),
          GoRoute(
            path: "/splash",
            name: SplashScreen.routeName,
            builder: (_, state) => SplashScreen(),
          ),
          GoRoute(
            path: "/login",
            name: LoginScreen.routeName,
            builder: (_, state) => LoginScreen(),
          ),
        ];

 

  1. 메인

    import 'package:actual/common/provider/go_router.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    
    void main() {
      runApp(
        ProviderScope(
          child: _App(),
        ),
      );
    }
    
    class _App extends ConsumerWidget {
      const _App({Key? key}) : super(key: key);
    
      // 라우팅시 BuildContext 사용하기 위한 구조
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        final router = ref.watch(routerProvider);
    
        return MaterialApp.router(
          theme: ThemeData(
            fontFamily: "NotoSans",
          ),
          debugShowCheckedModeBanner: false,
          routerConfig: router,
        );
      }
    }

 

  1. 라우트 프로바이더 (go_router. dart)

    import 'package:actual/user/provider/auth_provider.dart';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    import 'package:go_router/go_router.dart';
    
    final routerProvider = Provider<GoRouter>((ref) {
      final provider = ref.read(authProvider);
    
      return GoRouter(
        routes: provider.routes,
        initialLocation: "/splash",
        refreshListenable: provider,
        redirect: (context, state) {
          return provider.redirectLogic(state);
        },
      );
    });
    

 

오류 로그

======== Exception caught by gesture ===============================================================
The following NoSuchMethodError was thrown while handling a gesture:
Class 'ConsumerStatefulElement' has no instance method 'go'.
Receiver: Instance of 'ConsumerStatefulElement'
Tried calling: go("/restaurant/5ac83bfb-f2b5-55f4-be3c-564be3f01a5b")

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1      RestaurantScreen.build.<anonymous closure>.<anonymous closure> (package:actual/restaurant/view/restaurant_screen.dart:17:21)
#2      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:275:24)
#3      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:654:11)
#4      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:311:5)
#5      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:281:7)
#6      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:167:27)
#7      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:469:20)
#8      GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:445:22)
#9      RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:331:11)
#10     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:400:7)
#11     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:363:5)
#12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:320:7)
#13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:293:9)
#14     _invoke1 (dart:ui/hooks.dart:158:13)
#15     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:382:7)
#16     _dispatchPointerDataPacket (dart:ui/hooks.dart:91:31)
Handler: "onTap"
Recognizer: TapGestureRecognizer#cc27d
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(158.8, 246.5)
  finalLocalPosition: Offset(142.8, 190.5)
  button: 1
  sent tap down
====================================================================================================
F/crash_dump32(30915): crash_dump.cpp:474] failed to attach to thread 188: Permission denied

답변 1

1

코드팩토리님의 프로필 이미지
코드팩토리
지식공유자

안녕하세요!

이건 코드 문제가 아니라 pubspec.yaml이 문제가 있거나 디펜던시 다운로드가 잘 안된 것 같습니다.

혹시 해결 못하셨으면 아래 링크 카카오채널에서 원격 신청해주시면 봐드릴게요!

오늘은 어렵고 내일 시간 맞춰볼 수 있을 것 같습니다.

https://links.codefactory.ai

감사합니다!

안녕하세요

근본적인 원인은 해결하지 못했습니다 ㅠㅠ

fluuter clean 및 cache 도 날려봤지만 같은 오류가 발생해서 아래와 같이 변환하는 코드를 추가해서 실습 중 입니다

하지만 매번 저 코드를 넣을 수는 없다고 생각이 들어서..

근본적인 해결을 할 수 있는 방법을 알려주시면 감사하겠습니다!

  1. 리스트 스크린

import 'package:actual/common/component/pagination_list_view.dart';
import 'package:actual/restaurant/component/restaurant_card.dart';
import 'package:actual/restaurant/provider/restaurant_provider.dart';
import 'package:actual/restaurant/view/restaurant_detail_screen.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class RestaurantScreen extends StatelessWidget {
  const RestaurantScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PaginationListView(
      provider: restaurantProvider,
      itemBuilder: <RestaurantModel>(context, index, model) {
        return GestureDetector(
          onTap: () {
            GoRouter goRouter = GoRouter.of(context); // context 강제 변환
            goRouter.goNamed(RestaurantDetailScreen.routeName,
                pathParameters: {"rid": model.id});
          },
          child: RestaurantCard.fromModel(model: model),
        );
      },
    );
  }
}

 

  1. pubspec.yaml 입니다

name: actual
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=3.0.5 <4.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  dio: ^5.2.1+1
  flutter_secure_storage: ^8.0.0
  json_annotation: ^4.8.0
  retrofit: '>=4.0.0 <5.0.0'
  logger: any  #for logging purpose
  flutter_riverpod: ^2.0.2
  riverpod_annotation: ^1.0.4
  skeletons: ^0.0.3
  go_router: ^7.0.1

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0
  build_runner: ^2.3.3
  json_serializable: ^6.6.0
  retrofit_generator: '>=5.0.0 <6.0.0'
  riverpod_generator: ^1.0.4

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  assets:
    - asset/img/misc/
    - asset/img/food/
    - asset/img/logo/
    - asset/rive/
    - asset/svg/icon/

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

  fonts:
    - family: NotoSans
      fonts:
        - asset: asset/fonts/NotoSansKR-Black.otf
          weight: 900
        - asset: asset/fonts/NotoSansKR-Bold.otf
          weight: 700
        - asset: asset/fonts/NotoSansKR-Medium.otf
          weight: 500
        - asset: asset/fonts/NotoSansKR-Regular.otf
          weight: 400
        - asset: asset/fonts/NotoSansKR-Light.otf
          weight: 300
        - asset: asset/fonts/NotoSansKR-Thin.otf
          weight: 100

 

코드팩토리님의 프로필 이미지
코드팩토리
지식공유자

안녕하세요! 문제를 찾은 것 같습니다. 현재 itemBuilder에 있는 context와 build 함수에 있는 context의 이름이 같아서 그렇습니다. itemBuilder의 context는 _로 대체해서 실행해보세요!

아 그러게요 ㅎㅎ

말씀하신대로 context 이름의 중복 문제였습니다

해당 부분 변경하니까 잘 작동합니다

감사합니다~

강의 수집가님의 프로필 이미지
강의 수집가

작성한 질문수

질문하기