Building a Loading Screen in Flutter with HTTP Requests

In this blog post, we will explore how to create a loading screen in a Flutter application while fetching data from an API using HTTP requests. We'll build a simple example that demonstrates the process step by step.


Prerequisites:

Before diving into the implementation, make sure you have Flutter and Dart SDK installed on your machine. Basic knowledge of Flutter and asynchronous programming in Dart is also helpful.

Step 1: Setting Up the Project

To get started, create a new Flutter project in your preferred IDE. Open the project and replace the default code in the main.dart file with the following code snippet:

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

void main() {
  runApp(MyApp());
}

This code imports the required packages for building the loading screen and making HTTP requests.

Step 2: Creating the MyApp Widget

Inside the main.dart file, define a new class called MyApp, which extends StatelessWidget. This widget represents the root of our application and sets the app's title and theme.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Loading Screen Example',
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: MyHomePage(),
    );
  }
}

Step 3: Building the Home Page

Next, let's create the home page of our application. Create a new class called MyHomePage, which extends StatefulWidget. This allows us to manage the state of the widget.

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Step 4: Managing State in _MyHomePageState

Inside the _MyHomePageState class, we need to define two variables: isLoading and text. The isLoading variable keeps track of whether the data is being fetched, while the text variable stores the fetched data.

class _MyHomePageState extends State<MyHomePage> {
  bool isLoading = true;
  String text = '';

Step 5: Fetching Data from the API

In the _MyHomePageState class, override the initState() method. This method is called when the widget is first created. Inside it, call a fetchData() method to make an HTTP request and update the state accordingly.

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

Next, define the fetchData() method. Use the http package to send a GET request to the desired API endpoint. In this example, we're using 'https://jsonplaceholder.typicode.com/posts'. Handle the response based on its status code. If the response is successful (status code 200), decode the response body and extract the necessary data.

  Future<void> fetchData() async {
    final response =
        await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      final firstPost = data[1]['title'];
      setState(() {
        text = firstPost;
        isLoading = false;
      });
    } else {
      setState(() {
        text = 'Error loading data';
        isLoading = false;
      });
    }
  }

Step 6: Building the User Interface

In the build() method of the _MyHomePageState class, define the UI for the home page. Use the Scaffold widget to create a basic app layout with an AppBar and a body.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading Screen Example'),
      ),
      body: Center(
        child: isLoading
            ? CircularProgressIndicator() // Show loading indicator while data is being fetched
            : Text(text), // Display the fetched text
      ),
    );
  }
}

If isLoading is true, display a CircularProgressIndicator to indicate that data is being loaded. Otherwise, display the fetched text.

Step 7: Running the Application

Save the changes and run the application on an emulator or a physical device. You should see a loading screen with a circular progress indicator initially. Once the data is fetched successfully, the loading screen disappears, and the fetched text is displayed.

Full Source code

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Loading Screen Example',
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isLoading = true;
  String text = '';

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

  Future<void> fetchData() async {
    final response =
        await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      final firstPost = data[1]['title'];
      setState(() {
        text = firstPost;
        isLoading = true;
      });
    } else {
      setState(() {
        text = 'Error loading data';
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading Screen Example'),
      ),
      body: Center(
        child: isLoading
            ? CircularProgressIndicator() // Show loading indicator while data is being fetched
            : Text(text), // Display the fetched text
      ),
    );
  }
}

In this blog post, we've learned how to create a loading screen in Flutter while making HTTP requests. We've built a simple example that demonstrates the process of fetching data and updating the UI accordingly. By using the CircularProgressIndicator, users are provided with feedback on the ongoing data retrieval process. With this knowledge, you can enhance your Flutter applications by implementing loading screens and handling asynchronous data fetching efficiently.

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

How to Make a Dynamic and Trending ListView with Flutter Widgets?

Understanding API integration with Getx State management