Front-End/Flutter

[Flutter] 앱 통신 방법 및 에러 처리

Voyage_dev 2023. 10. 28. 17:13

설정

// pubspec.yaml

dependencies:
  http: ^0.13.4
// main.dart

import 'package:http/http.dart' as http;
import 'dart:convert'; // -> JSON 형태를 일반 자료형으로 변환해 주는 함수모음집
// android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
  • 인터넷 사용 허락 코드
  • IOS는 필요 없다

Get 요청

void getData() async {
  var result = await http.get( Uri.parse('요청할url') )
  print(result.body)
}

but…

  • 가져온 데이터 대부분은 JSON 형태이다
  • 서버랑 주고받는 데이터는 오직 문자만 가능 즉, 리스트나 객체 형태는 불가능 (”” 큰따움표로 전부 감싸거나)
  • 그래서 조작하기 쉽게 리스트나 map 같은 자료로 변환하려면 json.Decode()로 변환후에 쓰면 된다
jsonDecode(result.body)

추가

try catch 문으로 모든 에러를 체크할 때 fluttertoast로 메시지 띄우는 방법

dependencies:
  fluttertoast: ^8.2.2
import 'package:fluttertoast/fluttertoast.dart';
void getData() async {
    try{
      var result = await http.get(Uri.parse('<https://codingapple1.github.io/app/data.json>'));
      setState(() {
        feed = jsonDecode(result.body);
      });
      print(jsonDecode(result.body));
    }
    catch(e){
      print(e);
      showToast();
    }
  }

void showToast(){
    Fluttertoast.showToast(
        msg: "오류가 발생했습니다",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );
  }