CodeBlanks Logo Icon CodeBlanks

Summary - http

Combine http.get and statusCode to fetch data.

Summary - http

In this section you learned three things: with the http package you make REST requests; with http.get you fetch data; with response.statusCode you do error handling.

final response = await http.get(
  Uri.parse('https://api.example.com/data'),
);
if (response.statusCode == 200) {
  print(response.body);
}

Combining these, you build a data fetching screen.

Practice Build a data fetching screen

Write an async method veriCek. Make a request with http.get(Uri.parse('https://api.example.com/kullanici')). If response.statusCode == 200, print 'gövde: ${response.body}'; otherwise print 'hata: ${response.statusCode}'. In main, await veriCek and call print('bitti').

Starter code

main.dart
import 'package:http/http.dart' as http;

// veriCek: async metot ekle

void main() async {
  // veriCek'i çağır ve mesaj yazdır
}

Sample solution

main.dart
import 'package:http/http.dart' as http;

Future<void> veriCek() async {
  final response = await http.get(Uri.parse('https://api.example.com/kullanici'));
  if (response.statusCode == 200) {
    print('gövde: ${response.body}');
  } else {
    print('hata: ${response.statusCode}');
  }
}

void main() async {
  await veriCek();
  print('bitti');
}

Expected output

gövde: {"isim":"Ayşe"}
bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is done if statusCode is 200 on the data fetching screen?

  • The request is sent again
  • The app is closed
  • An error message is shown
  • response.body is processed and shown Correct answer

Explanation: If statusCode is 200, the request succeeded; response.body is processed and reflected to the screen.

2 Complete the http.get call

Question
final response = await http.____(Uri.parse('https://api.example.com/veri'));
Answer
final response = await http.get(Uri.parse('https://api.example.com/veri'));

Explanation: http.get takes a Uri and returns a Response; it is used to fetch data.

3 http section parts

Term Meaning
http Package making REST requests
get Data fetching method
statusCode Property giving HTTP status code
Response Request return object

All lessons in Intermediate