본문 바로가기
Flutter

[Flutter] How to go back and request API to refresh the previous page : 이전페이지 이동 후 API 호출

by hymndaniel 2023. 1. 31.

Context

FirstPage에서 조회되는 내용을 편집을 하려고 SecondPage로 Route.

SecondPage에서 원하는 내용으로 편집하고 서버 DB에 데이터 Post,  편집 완료 버튼을 누르면 FirstPage로 이동

FirstPage에서는 편집된 내용이 조회

 

Implement

FirstPage의 Route하는 위젯에서 SecondPage의 처리결과를 받아서 정상일때 API를 호출

 

FirstPage

// FirstPage의 편집 버튼
TextButton(
  onPressed: () async {
    // SecondPage에서 다시 돌아올때 결과를 result 변수에 받기. 이때, await로 받아 올때까지 기다렸다가 처리
    final result = await Get.toNamed('/editFarmWork',
        arguments: {"selectedDate": DateFormat('yyyy-MM-dd').format(_selectedDay!)});
    // SecondPage에서 처리된 결과가 정상일때(response.statusCode ==200) api를 호출
    if (result == 200) {
      await updateEvent(DateFormat('yyyy-MM').format(_selectedDay!));
    }
  },
  child: Container(
    decoration: BoxDecoration(
      color: Color(0xff0176f9),
      borderRadius: BorderRadius.circular(10),
    ),
    child: Padding(
      padding: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
      child: Text(
        '편집',
        style: TextStyle(
          color: Colors.white,
          fontSize: 16,
          fontFamily: 'NotoSansCJKKR',
          fontWeight: FontWeight.w500,
        ),
      ),
    ),
  ),
),

 

SecondPage

//SecondPage의 편집완료 버튼
TextButton(
  onPressed: () async {
    Map<String, dynamic> rawMap = {};
    //=========== 데이터 가공, 처리코드 ===========
    final responseResult = await httpHelper.editDiaryEvents(rawMap); // response.statusCode
    Get.back(result: responseResult);
  },
  child: const Center(
    child: Text(
      '편집 완료',
      style: TextStyle(
        color: Colors.white,
        fontSize: 16,
        fontFamily: 'NotoSansCJKKR',
        fontWeight: FontWeight.w500,
      ),
    ),
  ),
),
 

 

시행착오

SecondPage에서 처리 결과를 statusCode로 받지 않았을때는 프론트에서 refresh가 반영이 되지 않았는데, 서버 DB에서 처리하는데 시간이 소요가 되기 때문으로 추측했다.

그래서 서버 DB가 완전히 처리할때까지 await으로 기다렸다가 처리된 상태를 받아서 처리하기로 했다.

 
728x90