반응형
코드 작성
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// API에서 가져온 데이터를 저장할 리스트
List<dynamic> _data = [];
// API를 호출하여 데이터를 가져오는 함수
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
// 만약 요청이 성공했다면
if (response.statusCode == 200) {
// JSON 형식의 응답을 Dart 객체로 변환하여 데이터 리스트에 저장
setState(() {
_data = json.decode(response.body);
});
} else {
// 요청이 실패한 경우 에러 메시지 출력
print('Failed to load data: ${response.statusCode}');
}
}
@override
void initState() {
super.initState();
// initState() 메서드에서 데이터 가져오는 함수 호출
fetchData();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('REST API Communication'),
),
body: _data.isEmpty
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
// 리스트뷰 아이템에 데이터를 출력
return ListTile(
title: Text(_data[index]['title']),
subtitle: Text(_data[index]['description']),
);
},
),
),
);
}
}
반응형
'개발 > Flutter' 카테고리의 다른 글
Flutter 플러터 Textfield 사용법 간단 구현 (0) | 2024.03.15 |
---|---|
Flutter 플러터 음악 앱 만들기 Music (0) | 2024.03.15 |
Flutter 플러터 날씨 앱 간단 구현 Weather (0) | 2024.03.15 |
플러터 Flutter 스크롤 뷰 간단 구현 Scroll View (0) | 2023.11.28 |
플러터 Flutter 스톱워치 간단 구현 Stopwatch (0) | 2023.05.30 |
플러터 Flutter run : arch -x86_64 sudo gem install ffi 에러 (0) | 2023.04.01 |
플러터 Flutter Cannot find xcode build 에러가 뜰경우 (0) | 2023.04.01 |
플러터 Flutter 콘솔 유용한 명령어 모음 VSCode Console (0) | 2023.03.31 |
댓글