Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I encounter a Late Field initialization error when using Socket-IO #56

Open
gachagajnr opened this issue Jun 13, 2023 · 5 comments
Open
Assignees
Labels
bug Something isn't working

Comments

@gachagajnr
Copy link

gachagajnr commented Jun 13, 2023

This is the error I am encountering on calling find query on feathers Js server from flutter app both running on local machine

I/flutter ( 7821): │ ⛔ Unexpected error ::: LateInitializationError: Field 'scketio' has not been initialized.

The error comes from this code below;
This code from my provider;

  Future<APIResponse<List<ActivityI>>> getActivities() async {
    List<ActivityI>? messages;
    String? error;
    try {
      Map<String, dynamic> response = await socketIOClient.scketio.find(
        serviceName: "activities",
        query: {},
      );
      logger.i(response.toString());
      messages = List<Map<String, dynamic>>.from(response["data"])
          .map((map) => ActivityI.fromMap(map))
          .toList();
    } on FeatherJsError catch (e) {
      logger.e("FeatherJsError error ::: Type => ${e.type} ::: Message => ${e.message}");
      error = "Unexpected FeatherJsError occurred, please retry!";
    } catch (e) {
      logger.e("Unexpected error ::: ${e.toString()}");
      error = "Unexpected error occurred, please retry!";
    }
    return APIResponse(errorMessage: error, data: messages);
  }

// Below is how I have initialized my socket-io client for the flutter app;

FlutterFeathersjs socketIOClient = FlutterFeathersjs();

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  socket.Socket io = socket.io(API.baseUrl, <String, dynamic>{
    'transports': ['websocket'],
  });
  socketIOClient.configure(FlutterFeathersjs.socketioClient(io));

  runApp(MultiProvider(providers: [
    ChangeNotifierProvider(create: (_) => UserProvider()),
    ChangeNotifierProvider(create: (_) => ThemeProvider()),
    ChangeNotifierProvider(create: (_) => ActivityProvider()),

  ], child: const MyApp()));
}

//Currently using flutter_feathersjs: 4.1.5
//                       socket_io_client: ^2.0.1

//  This is my code calling on getActivities from ActivityProvider

 fetchActivities() async {
    context.read<ActivityProvider>().getActivities().then(
      (response) {
        isLoading = false;
        if (response.errorMessage == null) {
          setState(() {
            activities = response.data!;
          });
        } else {
          setState(() {
            error = response.errorMessage;
          });
        }
      },
    );
  }

  @override
  void initState() {
    isLoading = true;
    fetchActivities();
    super.initState();
  }

Currently running debug app on memu emulator

@gachagajnr gachagajnr added the bug Something isn't working label Jun 13, 2023
@gachagajnr gachagajnr changed the title I encounter a Late Field initialization error when using socket io I encounter a Late Field initialization error when using Socket-IO Jun 13, 2023
@Dahkenangnon
Copy link
Owner

You may probably mis initiate the flutter feathers js client.

I dont realy understand your code:

  1. Where does come this code ?
 @override
  void initState() {
    isLoading = true;
    fetchActivities();
    super.initState();
  }
  1. Is it in your main() function . If it's, why does you provide a such method where according to me, state are relative to widget ?

More informations can help because from now, I cannot reproduce the given issue

  1. Where is fetchActivities method defined ?

@Dahkenangnon Dahkenangnon pinned this issue Jun 14, 2023
@gachagajnr
Copy link
Author

gachagajnr commented Jun 14, 2023

The code above call this this code below which is from activities_provider.dart

class ActivityProvider with ChangeNotifier{
//this is the method on init state in main.dart that is being called by fetchActivities


Future<APIResponse<List<ActivityI>>> getActivities() async {
    List<ActivityI>? messages;
    String? error;
    try {
      Map<String, dynamic> response = await socketIOClient.scketio.find(
        serviceName: "activities",
        query: {},
      );
      logger.i(response.toString());
      messages = List<Map<String, dynamic>>.from(response["data"])
          .map((map) => ActivityI.fromMap(map))
          .toList();
    } on FeatherJsError catch (e) {
      logger.e("FeatherJsError error ::: Type => ${e.type} ::: Message => ${e.message}");
      error = "Unexpected FeatherJsError occurred, please retry!";
    } catch (e) {
      logger.e("Unexpected error ::: ${e.toString()}");
      error = "Unexpected error occurred, please retry!";
    }
    return APIResponse(errorMessage: error, data: messages);
  }
}

//I am accessing getActivities() method using provider
 fetchActivities() async {
    context.read<ActivityProvider>().getActivities().then(
      (response) {
        isLoading = false;
        if (response.errorMessage == null) {
          setState(() {
            activities = response.data!;
          });
        } else {
          setState(() {
            error = response.errorMessage;
          });
        }
      },
    );
  }

@gachagajnr
Copy link
Author

The logged error looks like this
I/flutter (31361): │ ⛔ Unexpected error ::: LateInitializationError: Field 'scketio' has not been initialized.
when I log response and error from this method

Future<APIResponse<List>> getActivities() async {
List? messages;
String? error;
try {
Map<String, dynamic> response =
await socketIOClient.scketio.find(query: {}, serviceName: 'activities');
messages = List<Map<String, dynamic>>.from(response["data"])
.map((map) => ActivityI.fromMap(map))
.toList();
} on FeatherJsError catch (e) {
logger.e(
"FeatherJsError error ::: Type => ${e.type} ::: Message => ${e.message}");
error = "Unexpected error occurred, please retry!";
} catch (e) {
logger.e("Unexpected error ::: $e");
error = "Unexpected error occurred, please retry!";
}
return APIResponse(errorMessage: error, data: messages);
}
}

This below is my socket-io initialization in main.dart

FlutterFeathersjs socketIOClient = FlutterFeathersjs();

void main() {
WidgetsFlutterBinding.ensureInitialized();

socket.Socket io = socket.io(API.baseUrl, <String, dynamic>{
'transports': ['websocket'],
"forceNew": true
});
socketIOClient.configure(FlutterFeathersjs.socketioClient(io));

@Dahkenangnon
Copy link
Owner

Can you please, format correctly your code (snippets) in your previous comments. It's hard to look in up to your code.

Just use
```dart
// Put your code here.
```

@gachagajnr
Copy link
Author

dart
//activity provider
class ActivityProvider with ChangeNotifier{
//this is the method on init state in main.dart that is being called by fetchActivities


Future<APIResponse<List<ActivityI>>> getActivities() async {
    List<ActivityI>? messages;
    String? error;
    try {
      Map<String, dynamic> response = await socketIOClient.scketio.find(
        serviceName: "activities",
        query: {},
      );
      logger.i(response.toString());
      messages = List<Map<String, dynamic>>.from(response["data"])
          .map((map) => ActivityI.fromMap(map))
          .toList();
    } on FeatherJsError catch (e) {
      logger.e("FeatherJsError error ::: Type => ${e.type} ::: Message => ${e.message}");
      error = "Unexpected FeatherJsError occurred, please retry!";
    } catch (e) {
      logger.e("Unexpected error ::: ${e.toString()}");
      error = "Unexpected error occurred, please retry!";
    }
    return APIResponse(errorMessage: error, data: messages);
  }
}
//socket-io initialization  method in main.dart
FlutterFeathersjs socketIOClient = FlutterFeathersjs();

void main() {
WidgetsFlutterBinding.ensureInitialized();

socket.Socket io = socket.io(API.baseUrl, <String, dynamic>{
'transports': ['websocket'],
"forceNew": true
});
socketIOClient.configure(FlutterFeathersjs.socketioClient(io));

//then in activities.dart page am calling fetchActitivites() on page init 
fetchActivities() async {
    context.read<ActivityProvider>().getActivities().then(
      (response) {
        isLoading = false;
        if (response.errorMessage == null) {
          setState(() {
            activities = response.data!;
          });
        } else {
          setState(() {
            error = response.errorMessage;
          });
        }
      },
    );
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants