[Flutter] #3 http interface
- Study/FrontEnd
- 2021. 7. 27. 01:19
follow the flutter.dev homepage tutorial guide.
- I think, it's the best way to learn flutter that learn from
flutter.dev
website. - This article is based on flutter.dev
use the http package on flutter
Let's use rest api protocol on flutter.
- First, we need to add
http
package. - Seconde, import package on source.
import 'package:http/http.dart' as http
. as http is optional. - Third, add android.permission.INTERNET for android.
<uses-permission android:name="android.permission.INTERNET" />
in AndroidManifest.xml.
- First, we need to add
You can download http package write the command
flutter pub add http
.
Make a api request
- Write this sample source.
Future<http.Response> fetchAlbum() {
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
- I try it on other source, not
main.dart
. Maybe flutter framework have a design patten make a folder and sources, but I don'k know right now. In react, I wrote the api codes inapi.js
. I try it again.
Make a model class
- I don't know whether it called
model
or not in flutter, I use the wordmodel
express the class. - The sample api url
~/ablums/1
has 3 fielduserId, id, title
. So we need to make a class has 3 value.
class Album {
final int userId;
final int id;
final String title;
Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
- I wrote this code
model.dart
. It's my way lol.
Change a api request class
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
- We need to change the code
fetchAlbum
to return Album class from return http.response class.
Test it
class ApiTestWidget extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _ApiTestWidgetState();
}
}
class _ApiTestWidgetState extends State<ApiTestWidget>{
late Future<Album> futureAlbum;
@override
void initState(){
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot){
if(snapshot.hasData){
return Container(
padding: EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(snapshot.data!.id.toString()),
Text(snapshot.data!.userId.toString()),
Text(snapshot.data!.title.toString()),
],
),
);
Text(snapshot.data!.title);
}else if(snapshot.hasError){
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
);
}
}
- This widget is show response of api call. The core function
fetchAlbum()
is ininitState()
. It runs one time when the app run. - They don't recommand calling in
build()
. Because, It runs often.
Update data over api call
- Last post (#2 stateful widget) we made a widget has a state. When I tapped the container, the state value changes. How does it make with api call.
- This is based on fultter.dev
ElevatedButton(onPressed: (){
setState(() {
futureAlbum = fetchAlbum2();
});
}, child: const Text('change')),
- It's simple than I think. Just add the code
setState
anywhere in widget.
반응형
'Study > FrontEnd' 카테고리의 다른 글
[Flutter] Retrofit 적용해서 api 호출하기 (0) | 2021.08.26 |
---|---|
[Flutter] Flutter Bloc 디자인 패턴 적용해서 rest api 호출하기 (0) | 2021.08.06 |
[Flutter] #2 stateful widget (0) | 2021.07.22 |
[Flutter] #1 flutter layout (0) | 2021.07.18 |
[Flutter] 플러터 레이아웃 튜토리얼 진행 (0) | 2021.05.23 |