Showing posts with label Mobile App. Show all posts
Showing posts with label Mobile App. Show all posts

Friday, 21 October 2022

Flutter Dart Error: Can't load Kernel binary - Invalid kernel binary

During working with Flutter, Error "Can't load Kernel binary" may arise unexpectedly after we make some changes to the application. This error is often confusing for developers because it often does not specify a clear cause. Even if you haven't done anything wrong, mistakes can still appear spontaneously. With luck, cleaning the project can fix this problem, but in many cases it doesn't work.

Example of an error message:

[ERROR:flutter/shell/common/shell.cc(197)] Dart Error: Can't load Kernel binary: Invalid kernel binary: Indicated size is invalid.
   .../runtime/runtime_controller.cc(385)] Could not create root isolate
   ./android/android_shell_holder.cc(138)] Could not launch engine in configuration.
  

Reason:

Android Studio's compiler sometimes doesn't work as expected, so the process of linking libraries to compile Dart source code may encounter errors that distort the project's configuration paths. This results in errors during or after compilation with cryptic errors, even errors reported that seem absurd, unrelated to the problem. (It appears to be similar to the bug in Android Studio's Dart code suggestion function. In many cases Android Studio suggests inserting const or required keywords but inserts these keywords in the wrong place. which it is suggested.).
Once errors of this type arise, it is often cached in the project, so many times we try to find ways to not handle the error, but sometimes it suddenly disappears and cannot be re-appeared.

"Dart Error: Can't load Kernel binary: Invalid kernel binary: Indicated size is invalid."

Solve it

Please try the following steps one by one until the problem is resolved

Step 1: Clear project cache
Completely close the application in the virtual machine.
In the main project directory, run the command: "flutter clean"
Then run "flutter pub get" again to update the libraries. 
Rebuild the project to see if the error has been resolved, You can also try to change a little bit in the application's code to make sure the application has been rebuilt and not loaded from the cache. If the problem is not resolved, try step 2

Step 2: Clear Flutter SDK Cache
Go and delete all files in the cache folder of Flutter SDK.
"...flutter/bin/cache"
As required when installing, the Flutter SDK is usually installed in the C drive. For example: C:/flutter
You can also easily find the path to the Flutter SDK in the ".flutter-plugins" file inside your project.
After clearing the cache, run the "flutter doctor" command again to let flutter update the libraries (you can run "flutter doctor" from anywhere).
Re-open Project to see if the problem has been resolved. If not, continue with step 3.

Step 3: Rollback of previous project changes
Try reversing some of the last changes you made to the project's source code. (Remember to save those changes because you can still use them normally if they're not wrong.) Reversing changes, creating changes in the project's source code can help clear caches and miscompiled configuration fragments.
If the error is still not resolved when you have reversed the small segments then try some higher level change in the file "main.dart"

Note: In the process of fixing errors, you should not use "hot restart"

If there is anything more to share in this situation, please leave information in the comment section so we can discuss.

Sunday, 21 August 2022

[Flutter] Async Function vs Normal Function in Dart, How do they work?

 "Synchronous", "asynchronous", "await" and "asynchronous functions" are very confusing concepts when used in Flutter. For ease of explanation, in this article we will analyze two types of Flutter functions: Normal Function and Async Function. We will learn how these two types of functions work.

Ficture 1: Flutter/Dart async work flow

Normal Function and Async Function

The Dart language that Flutter uses inherits many features from Javascript. Dart's handling of synchronous and asynchronous jobs is also very similar to Javascript. There are two types of functions in the Dart language:

* Normal Function:

A function in Dart is declared as follows:


String doSomthing(){
    print('This is a normal Function');
    // do somthing
    return 'Done!';
}

* Async Function:

Async functions are functions declared with the async keyword at the end. 


String getApiContent() async{
    print('Async function loading api from Server');
    final response = await http.get(Uri.parse('https://codesiri.com/search/?q=api'));
    return response.body;
}
The difference of Async functions from normal functions is that in an Async function you will be able to use the await keyword to wait for another function to finish executing. Also, an Async doesn't return an immediate result, it just returns a Future.

Dart is an asynchronous language

By default, Dart always tries to process everything asynchronously whether it is an async function or a normal function. Let's analyze the example depicted in Figure 1.

Like other programming languages, DArt will also process the source code line by line from top to bottom. Even when encountering an Async function it continues to deal with the same logic. That's why in the example we see line 1 and line 2 in asyn function callApi still being executed. "Async" appears only when an actual async event occurs (http.get).

Inside an Async function when encountering a "real" async event (a predefined async event by Dart, not a self-created async function) there are 2 options.

Case 1: you can use the await keyword to wait until the async event completes and return the result. The current async function will break at that location. You did not read it wrong, Exactly, the async function will be interrupted at that point, not a new thread or process is initialized to run in the background at this time to continue the async task we are expecting. (You can use additional tools like Charles to verify this.) Of course Dart has kept in mind that there is an Async event still pending. Next Dart will return to the main program to continue to execute the next lines of code. That's why we see the sleep function being executed immediately followed by lines 3, 4, 5 being executed. After the main program has completed, Dart returns to continue processing asynchronous events and the next line of code in the async function.

Case 2: if you don't use await keyword before async event. Just like the case of 1 Dart will remember the pending asynchronous event, but next Dart will continue to execute the next code in the current async function as if nothing happened.


import 'package:http/http.dart' as http;
import 'dart:io';

void main(){	
  print('Line 1 - done !');
  var apiResult = callApi();
  sleep(Duration(seconds: 15)); // Test to monitor async task
  print('Line 3 - done !');
  normalFunction();
  print('Line 5 - done !');
}

Future callApi() async{
  print('Line 2 - Async Function callApi called');
  normalFunction2();
  print('==>A: Line 2 - Line 2 function callApi');
  final response = await http.get(Uri.parse('https://codesiri.com/search/?q=api'));
  print('==>A: Line 3 - call api done !');
  print('==>A: Line 4 - done !');
  return 'Done !';
}

void normalFunction1(){
  print('Line 4 - This is normalFunction1');
}
void normalFunction2(){
  print('==>A: Line 1 - This is normalFunction2');
}

Result:


I/flutter (21546): Line 1 - done !
I/flutter (21546): Line 2 - Async Function callApi called
I/flutter (21546): ==>A: Line 1 - This is normalFunction2
I/flutter (21546): ==>A: Line 2 - Line 2 function callApi
I/flutter (21546): Line 3 - done !
I/flutter (21546): Line 4 - This is normalFunction1
I/flutter (21546): Line 5 - done !
I/flutter (21546): ==>A: Line 3 - call api done !
I/flutter (21546): ==>A: Line 4 - done !

Dart is a single-threaded programming language

The reason Dart has to handle such complex asynchronous events is because it was designed to be a single-threaded language. By default our entire Flutter application runs on a single Dart thread. You will also still be able to create additional threads to actively handle parallel or background tasks, but then you will have to deal with the problems that arise.

Summary

When it encounters an async event, Dart will always push it to the bottom to wait for it to be processed. If there is await before the async call, all code that follows will also be pushed to the bottom to wait with it. Otherwise the next lines of code will still be treated as if nothing happened. Understanding how Dart's async works will help you optimize your application.