뷰모델 생성자로 리스트 불러오
219
작성자 없음
작성한 질문수 0
class StoreViewModel with ChangeNotifier {
String? regionName = '';
String barName = '지역별 서점';
bool isLoading = false;
final StoreRepository repository;
StoreViewModel(this.repository) {
print('생성자호출');
_loadSimpleStores();
print(stores);
}
List<SimpleStore> stores = [];
void onEvent(StoreEvent event, BuildContext context) {
event.when(touchTile: (id) async {
StoreInfo store = await repository.getStoreInfo(id);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StoreDetailScreen(storeDetail: store)),
);
}, searchStore: (query) async {
});
}
//지역 전체
Future<void> _loadSimpleStores() async {
isLoading = true;
notifyListeners();
stores = await repository.getStores();
isLoading = false;
notifyListeners();
}
}
---------------------------------------------
class StoreViewScreen extends StatefulWidget {
StoreViewScreen({
super.key,
this.barName,
this.regionName,
});
String? barName;
String? regionName;
@override
State<StoreViewScreen> createState() => _StoreViewScreenState();
}
class _StoreViewScreenState extends State<StoreViewScreen> {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
final customerInfoViewModel = context.watch<CustomerInfoViewModel>();
final storeViewModel = context.watch<StoreViewModel>();
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
storeViewModel.barName,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.close),
),
),
body: Column(children: [
//입력창 + 검색창
Container(
child: Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey), // 테두리 색상 설정
borderRadius: BorderRadius.circular(8.0), // 테두리 둥글기 설정
),
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: '텍스트를 입력하세요.',
// 힌트 텍스트
contentPadding: EdgeInsets.all(12.0),
// 텍스트 입력 필드 내부의 여백 설정
border: InputBorder.none, // 기본 테두리 제거
),
),
),
),
TextButton(onPressed: () {}, child: Text('검색'))
],
),
),
//지역 이름 or 내주변
Container(
child: Row(
children: [
Text(
storeViewModel.regionName ?? '내 주변',
style: TextStyle(
fontSize: customerInfoViewModel.screenHeight / 20,
fontWeight: FontWeight.bold),
),
Text(
'${storeViewModel.stores.length}가 검색 됨',
style: TextStyle(
fontSize: customerInfoViewModel.screenWidth / 20,
fontWeight: FontWeight.bold),
),
],
)),
//서점 리스트 표시
Expanded(
child: Container(
child: !storeViewModel.isLoading
? ListView.builder(
itemCount: storeViewModel.stores.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: StoreSimpleInfo(
id: storeViewModel.stores[index].id,
profileUrl: storeViewModel.stores[index].imageUrl,
storeName: storeViewModel.stores[index].name,
storeAddr: storeViewModel.stores[index].address,
category: storeViewModel.stores[index].category),
onTap: () {
storeViewModel.onEvent(
StoreEvent.touchTile(
storeViewModel.stores[index].id,
),
context,
);
},
);
},
)
: CircularProgressIndicator(),
),
),
]),
);
}
}
스크린을 열면 viewmodel 생성자로 리스트를 불러오고 싶은데 viewmodel 생성자가 작동을 안합니다 이유가 뭘까요 ㅠㅠ? 의존성주입 문제는 아닌것같아요
답변 1
0
혹시 생성자에서 print(stores) 로 확인했을 때 비어있어서 작동이 안 되었다고 느끼신 것이라면 _loadSimpleStores(); 가 비동기 함수기 때문에 await 없이는 print 문이 먼저 시작되기 때문에 당연히 비어있는 것으로 찍힐 것입니다.
그리고 생성자는 await 를 쓸 수 없으므로
_loadSimpleStores(); 함수의 마지막 라인에서 print 하시면 잘 확인되실 것입니다.
그래프 그리기 위한 API가 프리미엄 요금제를 구독해야만 가능하다고 합니다...ㅜㅜ
0
74
2
api 제한량 25회
0
100
2
프로젝트 전체 소스코드
0
62
2
DTO 작성시 freezed 3.0 변경 부분 문의
0
167
2
클린아키텍처 의존관계 관련
0
215
2
mapper 생성 시...
0
168
1
강의에 있는 모든 freezed를 제거해도 되나요?
0
257
2
수업과 관련이 없지만 물을 곳이 없어...교수님께 여쭙니다..
0
357
1
개남님 질문있씁니다! company_listing_entitiy가 왜 엔티티 인가요?
0
198
1
안녕하세요 디버그 모드 관련 여쭤볼게 있어요
0
293
1
다음 로드맵 질문
0
346
1
csv_parser라는 abstract를 작성하는 필요성이 궁금합니다
0
404
1
repository에 관하여
0
357
1
강의 예시에 대한 답변이 궁금합니다.
0
360
1
flutter 실행 관련 질문드립니다.
0
1060
1
폴더 구조에 대해 질문드립니다.
0
819
1
Repository test 관련해 질문이 있습니다.
0
262
1
stock_repository_impl.dart 에러
0
269
2
viewModel에서 context를 받는 행위 질문
0
382
1
stockApi 질문 드립니다.
0
178
1
stockApi 질문
0
260
1
라이브 템플릿 영상
0
314
1
StockApi 메서드 반환 타입에 대해
0
282
1
entity와 domain의 차이
0
4506
1





