How to fetch data from the internet in Flutter?

 I-Hub Talent: The Best Flutter Training in Hyderabad

Are you looking for the best Flutter training in Hyderabad to build a successful career in mobile app development? Look no further! I-Hub Talent is the top-rated Flutter training institute in Hyderabad, providing hands-on training with real-time projects and expert guidance. Our Flutter course in Hyderabad is designed to help beginners and experienced developers master the Flutter framework and build high-performance mobile applications for Android and iOS.

Why Choose I-Hub Talent for Flutter Training in Hyderabad?

✔ Industry-Expert Trainers – Learn from experienced professionals who have worked on real-world Flutter development projects.
✔ Hands-On Learning – Work on live projects and gain practical experience in building cross-platform mobile apps.
✔ Comprehensive Curriculum – Our Flutter training course in Hyderabad covers Dart programming, UI/UX design, API integration, Firebase, and state management using Provider and Bloc.
✔ Job-Oriented Training – We focus on industry-relevant skills to help you secure high-paying jobs in mobile app development.
✔ Placement Assistance – Get career support, resume building, and interview preparation to land your dream job.
✔ Affordable Fees & Flexible Timings – Our Flutter training in Hyderabad is designed to fit your schedule, whether you are a student or a working professional.

In Flutter, you typically fetch data from the internet (e.g., APIs, JSON data, etc.) using the http package.
Here’s a step-by-step explanation with an example:


1. Add Dependency

Open your pubspec.yaml and add:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.0   # check pub.dev for latest version

Then run:

flutter pub get

2. Import the Package

import 'package:http/http.dart' as http;
import 'dart:convert'; // for JSON decoding

3. Make a GET Request

Example: Fetching data from a JSON API (https://jsonplaceholder.typicode.com/posts)

Future<List<dynamic>> fetchPosts() async {
  final response =
      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {
    // Convert response body into JSON
    return jsonDecode(response.body);
  } else {
    throw Exception('Failed to load posts');
  }
}

4. Use in UI (with FutureBuilder)

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

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

class MyApp extends StatelessWidget {
  Future<List<dynamic>> fetchPosts() async {
    final response = await http.get(
      Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    );

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception("Failed to load posts");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Fetch Data Example")),
        body: FutureBuilder<List<dynamic>>(
          future: fetchPosts(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Center(child: Text("Error: ${snapshot.error}"));
            } else if (!snapshot.hasData) {
              return Center(child: Text("No data found"));
            } else {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  final post = snapshot.data![index];
                  return ListTile(
                    title: Text(post['title']),
                    subtitle: Text(post['body']),
                  );
                },
              );
            }
          },
        ),
      ),
    );
  }
}

5. Notes

  • For POST requests, you can use http.post() with a body and headers.

  • For more advanced networking (interceptors, caching, retries), you might use dio package instead of http.

  • Always handle errors (try/catch) for network failures.

  • If fetching sensitive data, consider using flutter_secure_storage for tokens.


👉 Do you want me to also show you how to fetch data with Dio (an alternative with more features), or just stick to the simple http example?

Read More

Explain StatefulWidget vs StatelessWidget in Flutter.

Visit I HUB TALENT Training Instituted in Hyderabad

Get Direction


Comments

Popular posts from this blog

How does Flutter build apps for iOS and Android?

How does Flutter manage app state effectively?

How to manage state in Flutter apps?