Search code examples
androidflutterdartresponsedio

Flutter Dio response null


Am using flutter Dio library for api calling and on registration page, after the api call for user creation the user is created on database but the response shows null.

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../../../services/dio_web_util.dart';
import '../models/first_page_reg_request.dart';

 

class DioClient {
  Future<Response?> userRegistration(
      {required RegisterInfoReq requestData}) async {
    Response? userData;
    try {
      Response userData =
          await WebUtil.createDio().post('/Candidate/RegisterCandidate', data: requestData);
      if (kDebugMode) {
        print('User Info: ${userData}');
      }
    } on DioError catch (e) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx and is also not 304.
      if (e.response != null) {
        if (kDebugMode) {
          print('Dio error!');
        }
        if (kDebugMode) {
          print('STATUS: ${e.response?.statusCode}');
        }
        if (kDebugMode) {
          print('DATA: ${e.response?.data}');
        }
        if (kDebugMode) {
          print('HEADERS: ${e.response?.headers}');
        }
      } else {
        // Error due to setting up or sending the request
        if (kDebugMode) {
          print('Error sending request!');
        }
        if (kDebugMode) {
          print(e.message);
        }
      }
    }
    return userData;
  }
}

Above code is used for the service.Here the userData is prints correct value. But the response is stored in another page and the function call for that page is

Response? userData= await apiClient.userRegistration(requestData: requestBody);
        if (kDebugMode) {
          print('User Info: ${userData}');
        }

 

here userData is null... 

Anybody have an idea about this??


Solution

  • You are declaring and returning following variable

    Response? userData;
    

    but initializing and printing a new variable

    Response userData =
    

    Initialize above declared variable otherwise null will be returned from future function.