Im trying to create an simple Network class on dart, to centralize all my calls to an specific API.
So i create an Service class, and create an mock and a get function using Dio.
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:playground/home/model/home.dart';
import 'package:playground/network/base/safe_call.dart';
import 'dart:convert';
import '../../base/api_result.dart';
import '../../base/network_error.dart';
class HomeServices {
final Dio _dio;
HomeServices(this._dio);
Future<Object> getHome() async {
try {
final response = await Dio().get("https://jsonplaceholder.typicode.com/posts");
// Parse the response data into a `Home` object
final homeData = Home.fromJson(response.data);
return homeData;
} catch (e) {
return networkError(e);
}
}
Future<Home> mockHome() async {
try {
String response = await rootBundle.loadString('assets/home.json');
Map<String, dynamic> homeMap = await jsonDecode(response);
var homeData = Home.fromJson(homeMap);
return homeData;
} catch (e) {
return Home(List.empty(), List.empty());
}
}
}
And another class called APIClient, to center all my services:
import 'package:playground/network/services/home/home_services.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class ApiClient {
late final Dio _dio = Dio()..interceptors.add(PrettyDioLogger(
request: true,
requestHeader: true,
requestBody: true,
responseHeader: false
));
late HomeServices homeServices = HomeServices(_dio);
}
and inside my repository class, i think i should use like this:
Future<Home> readJson() async {
await apiClient.homeServices.mockHome().then((value) {
return value;
}).catchError((error) {
return error;
});
}
But im getting the error:
: Error: A non-null value must be returned since the return type 'Home' doesn't allow null.
carousel_repository.dart:13
- 'Home' is from 'package:playground/home/model/home.dart' ('lib/home/model/home.dart').
home.dart:1
Future<Home> readJson() async {
Not really sure on whats wrong with the call.
3
Answers
Not sure about my answer, but I feel
readJson()
should returnHome
since the return is onlyHome
object.If function return is
Future<Home>
then we can return the response fromapiClient
.Try this :
The error you’re encountering is because the
readJson()
method is expected to return anon-null
value of typeHome
, but your current implementation does not provide a return value in all code paths.Try this: