0
0
Fluttermobile~5 mins

Why API calls fetch remote data in Flutter

Choose your learning style9 modes available
Introduction

API calls let your app get fresh information from the internet. This helps your app show the latest data without needing to update the app itself.

When you want to show weather updates from a weather service.
When your app needs to display news articles from a news website.
When you want to get user information stored on a server.
When your app needs to send or receive messages from a chat server.
When you want to load product details from an online store.
Syntax
Flutter
final response = await http.get(Uri.parse('https://example.com/data'));
if (response.statusCode == 200) {
  var data = jsonDecode(response.body);
  // use data
}
Use the http package to make API calls in Flutter.
Always check the statusCode to make sure the call worked.
Examples
Fetches user data from the given URL.
Flutter
final response = await http.get(Uri.parse('https://api.example.com/users'));
Checks if the call was successful and parses the JSON data.
Flutter
if (response.statusCode == 200) {
  var jsonData = jsonDecode(response.body);
}
Sample App

This app fetches a to-do item title from a remote API and shows it on the screen. It starts with 'Loading...' and updates when data arrives.

Flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _title = 'Loading...';

  @override
  void initState() {
    super.initState();
    fetchTitle();
  }

  Future<void> fetchTitle() async {
    final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      setState(() {
        _title = data['title'];
      });
    } else {
      setState(() {
        _title = 'Failed to load';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('API Call Example')),
        body: Center(child: Text(_title, style: TextStyle(fontSize: 24))),
      ),
    );
  }
}
OutputSuccess
Important Notes

API calls can take time, so use async/await to avoid freezing the app.

Always handle errors like network failures gracefully.

Use JSON decoding to convert the response into usable data.

Summary

API calls get fresh data from the internet for your app.

Use async calls and check response status to handle data safely.

Parsing JSON lets you use the data inside your app easily.