Search code examples
flutterdartandroid-studiogoflutter-getx

How to resolve 'null' error when fetching data in Flutter using GetX?


I'm following a Flutter tutorial to fetch data from a backend using the GetX package. Despite following the tutorial steps, I'm unable to retrieve data from the backend, and instead, I get a 'null' error in my terminal. Below is my implementation based on the tutorial, along with the responses I observed.

Code:

// Flutter code: DataController.dart
import 'package:flutter_golang_yt/services/service.dart';
import 'package:get/get.dart';

class DataController extends GetxController {
  DataService service = DataService();
  bool _isLoading = false;
  List<dynamic> _myData = [];

  Future<void> getData() async {
    _isLoading = true;
    Response response = await service.getData();
    _isLoading = false;
    if (response.statusCode == 200) {
      _myData = response.body;
      print("Data received: $_myData");
    } else {
      print("Failed to fetch data: Status code ${response.statusCode}");
    }
    update();
  }
}

// Service code: services.dart
import 'package:get/get.dart';

class DataService extends GetConnect implements GetxService {
  Future<Response> getData() async {
    return await get("http://localhost:3306/gettasks", headers: {
      'Content-Type': 'application/json; charset=UTF-8'
    });
  }
}

Error Description:

When I run the application, the expected result is to receive a list of tasks from the backend and print them. However, the output in my Flutter terminal is simply 'null', indicating no data is received or there is an issue with data handling.


Solution

  • The first thing you want to do is determine whether it's "response" or "response.statusCode" which is null. (print them out)

    Once you've determined that, you'll want to look at the documentation for "get" which will tell you the situations in which it that thing can be null.

    Also, if you're following this tutorial without much coding knowledge, I'd recommend starting with something simpler. Playing with asynchronous code and big 3rd party libraries is not a great starting place.