How to Get Plain Response from Dio Request in Flutter

In this example, we are going to show you how to get a non-encoded plain text response from the Dio request in Flutter. By default, Dio encodes the JSON response from REST API as a response. See the example below:

Normal Dio Request:

var dio = Dio();
var res = await dio.get("https://www.fluttercampus.com/json.php");

Output:

{error: false, msg: Hello World, data: [Hari, Krishna, John]}

Here, Dio fetches the data from the URL, encodes it to the Flutter map, and returned the response data. You can get this response without encoding using the following code:

var dio = Dio();
var res = await dio.get("https://www.fluttercampus.com/json.php", 
  options: Options( 
    responseType: ResponseType.plain,
  ));

Output:

{"error":false,"msg":"Hello World","data":["Hari","Krishna","John"]}

Here is the plain non-encoded plain JSON text from the REST API. You can get different response types by changing responseType at Options.

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

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> { 

  getData() async {
     var dio = Dio();
     var res = await dio.get("https://www.fluttercampus.com/json.php", 
         options: Options( 
            responseType: ResponseType.plain,
         ));

     if(res.statusCode == 200){

        print("Connection successful");
        print(res.data);
        //encoded response:
        //{error: false, msg: Hello World, data: [Hari, Krishna, John]}

        //Non encoded plain response:
        //{"error":false,"msg":"Hello World","data":["Hari","Krishna","John"]}
     }else{
       print("Error while connecting to server.");
     }
  }

  @override
  Widget build(BuildContext context) { 
    return  Scaffold(
          appBar: AppBar(
            title: Text("REST API"),
            backgroundColor: Colors.redAccent
          ),
          body: Container(
            padding: EdgeInsets.only(top:20, left:20, right:20),
            alignment: Alignment.topCenter,
            child: Column(
              children: [

                 ElevatedButton(
                  onPressed: () async {
                     getData();
                  }, 
                  child: Text("Get Data")
                ),
                
            ],)
          )
       );
  }
}

In this way, you can get a plain text response from Dio request in Flutter.

No any Comments on this Article


Please Wait...