dio in Flutter | How to use RestAPI in Flutter using dio ?

Flutter

Flutter Tutorial

Introduction

Flutter

Cross Platform

MVVM vs MVC vs MVP

Flutter Framework

Flutter Benefits

Flutter Comparison

Install Flutter in Win/Linux/Mac

Android Studio vs VsCode

Android Setup

VS Code Setup

VS Code Plugins

Android Studio Plugins

Flutter Widgets:

Flutter Basic Template

Flutter Commands

Top 10 Popular widgets

Flutter Stateless vs Stateful

Type of Widgets

Flutter Text widget

Flutter Text style

Textfield vs TextFormField

Flutter Scaffold

Flutter Container & SizedBox

Flutter Row & Column

Flutter Buttons

Flutter Stack

Flutter Forms

Flutter AlertDialog

Flutter Icons

Flutter Images

Flutter Drawer

Flutter ListView

Flutter GridView

Flutter Toast

Flutter Checkbox

Flutter Radio Button

Flutter Progress Bar

Flutter Tooltip

Flutter Slider

Flutter Table

Flutter SnackBar

Shimmer in Flutter

Bottom Navigation Bar in Flutter

Gesture Detector in Flutter

Error Handling in Flutter

DropDown in Flutter

Flutter Toggle

Auto Close Keyboard in Flutter

Screen size handling in Flutter

Flutter REST API

Flutter http

Flutter dio

dio vs http

Flutter Advance

Custom widget in Flutter

Flutter Navigator

Read Json in Flutter

Generate Excel in Flutter

Multiple Widgets in Flutter

Bottom sheet in Flutter

Copy to Clipboard in Flutter

Tab bar in Flutter

Code Editor in Flutter

Youtube Player in Flutter

Flutter App Development Tips

Flutter App version Update

Flutter Copy Text in App

Flutter Handle Null Value

Flutter Splash Screen

Flutter Disposable

Notification Listener

Flutter Switch Cases

Flutter Slivers

Flutter Custom App bar

Databinding in Flutter

Flutter Cards

Wrap vs Builder vs OverBarFlow

Flutter App Upgrade

GoogleMap vs FlutterMap

Circular progress contain Icon

DropDown Timer in Flutter

Flutter State management Comparison

Flutter vs Other Framework

Flutter Mixin

Passing values in Dart Files

WorkManager in Flutter

Flutter Database

Flutter Store Data

Suitable DB for Flutter

Backend for Flutter

SharedPreferences in Flutter

Flutter Token Expired Handling

Flutter Provider

Flutter Provider Tutorial

Flutter GetX

Flutter GetX tutorial

Flutter with Native

Flutter FFI

Flutter Testing

Flutter Tips

Best Practices

Reduce Flutter Screens

Tips to make app smart

Optimize App

Handle Multiple Pages

Interview Questions

Flutter 100 Interview Questions

Provider Interview Questions

GetX Interview Questions

BLoC Interview Questions

What is dio in Flutter ?

Dio is a powerful HTTP client for Dart and Flutter that supports features like interceptors, FormData, cancellation, and many more, It is used for connectivity flutter UI with backends such as Nodejs.

dio in flutter

How to use Dio in a Flutter app ?

First add dio package in pubspec.yaml file

dependencies:
  dio:   # use latest version

After adding the dependency to the pubspec file, you can use the dio package to make API requests.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Dio Flutter Example'),
        ),
        body: ApiExample(), //Here we call APiExample 
      ),
    );
  }
}

//This is API model which is used for retereive data in Object form from API
class Todo {
  final int userId;
  final int id;
  final String title;
  final bool completed;

  Todo({
    required this.userId,
    required this.id,
    required this.title,
    required this.completed,
  });

  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      completed: json['completed'],
    );
  }
}

class ApiExample extends StatefulWidget {
  @override
  _ApiExampleState createState() => _ApiExampleState();
}

class _ApiExampleState extends State<ApiExample> {
  final String apiUrl = 'https://jsonplaceholder.typicode.com/todos/1'; //For testing purpose we use this url which provide Json data
  late Todo todo;

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

  Future<void> fetchData() async {
    try {
      final response = await Dio().get(apiUrl);

      if (response.statusCode == 200) {
        // If the server returns a 200 OK response, parse the JSON
        setState(() {
          todo = Todo.fromJson(response.data);
        });
      } else {
        // If the server did not return a 200 OK response,
        // throw an exception.
        throw Exception('Failed to load data');
      }
    } catch (error) {
      print('Error: $error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          Text('API Data:'),
          SizedBox(height: 16),
//Here API data display 
          Text('Title: ${todo.title}'),

          SizedBox(height: 16),
          Text('Completed: ${todo.completed}'),
        ],
      ),
    );
  }
}

If you face any issue, please comment below, we will reply soon

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.