Responsive Ad Code Here

Header Ads

Flutter Dio Package Example

The dio package in Flutter is a powerful HTTP client library that simplifies making network requests and handling responses. It provides a high-level API with features like:


Basic HTTP requests:

    GET, POST, PUT, PATCH, DELETE, HEAD methods
    Easy URL parameter and query string handling
    Custom headers and body content

Advanced features:


    Interceptors for request and response modification
    Timeout handling
    Automatic content type detection
    Progress tracking
    Cookie management
    File uploading and downloading
    Multipart/form-data support
    JSON serialization and deserialization
    Custom error handling

 

Installation:

 
    dio: ^5.4.3+1 
 

or:

 
    flutter pub add dio
 

 

Code Example:

 
import 'package:dio/dio.dart'; // install package
import 'package:flutter/material.dart';

class DioFlutter extends StatefulWidget {
  const DioFlutter({super.key});

  @override
  State<DioFlutter> createState() => _DioFlutterState();
}

class _DioFlutterState extends State<DioFlutter> {
  dynamic jsonList; // varialble
  getHttp() async {
    var response = await Dio()
        .get('Api_KEY'); // get data
    if (response.statusCode == 200) {
      setState(() {
        jsonList = response.data as List;
      });
      // print(response);
    }
  }

  @override
  void initState() {
    getHttp(); // it's important other wise it data not show screen
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: jsonList == null
              ? 0
              : jsonList.length, // length the list and data if null show 0
          itemBuilder: (b, index) {
            return Text(jsonList[index]['parameterName']);
          }),
    );
  }
}