• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    미해결

뷰모델 생성자로 리스트 불러오

24.02.09 21:24 작성 조회수 81

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 하시면 잘 확인되실 것입니다.