작성
·
677
2
안녕하세요
강의 실습 중 오류가 발생해서 도움을 요청드립니다
현재 개발 중인 환경은 윈도우에서 안드로이드 시뮬레이터로 진행 중이며 IDE 는 인텔리제이를 사용하고 있고 gorouter 7.0.1 버전을 사용해서 실습을 하고 있습니다
GoRouter 설정 부분은 7.0.1 버전 실습 강좌를 참고해서 변경했고 정상적으로 로그인 및 스플래시 스크린까지 동작을 했습니다.
레스토랑 리스트에서 레스토랑 상세화면으로 이동하는 부분을 실습 중 오류가 발생합니다
첫번째. context에서 gorouter 관련 메소드가 자동완성이 안되며 실제로 동작도 하지 않습니다.
두번째. context.named() ,context.go() 둘 다 아래와 같은 오류가 나타납니다
레스토랑 스크린
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),
);
},
);
}
}
레스토랑 디테일 스크린
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,
),
),
);
}
}
라우터 설정부분 (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(),
),
];
메인
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,
);
}
}
라우트 프로바이더 (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이 문제가 있거나 디펜던시 다운로드가 잘 안된 것 같습니다.
혹시 해결 못하셨으면 아래 링크 카카오채널에서 원격 신청해주시면 봐드릴게요!
오늘은 어렵고 내일 시간 맞춰볼 수 있을 것 같습니다.
감사합니다!
안녕하세요
근본적인 원인은 해결하지 못했습니다 ㅠㅠ
fluuter clean 및 cache 도 날려봤지만 같은 오류가 발생해서 아래와 같이 변환하는 코드를 추가해서 실습 중 입니다
하지만 매번 저 코드를 넣을 수는 없다고 생각이 들어서..
근본적인 해결을 할 수 있는 방법을 알려주시면 감사하겠습니다!
리스트 스크린
pubspec.yaml 입니다