[Solved] LateInitializationError: Field has not been initialized Error in Flutter

In this post, we are going to show you how to solve "LateInitializationError: Field has not been initialized Error in Flutter" error in Flutter App. This error occurs when you have used the "late" variable before its initialization. See the different solutions below:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════
The following LateError was thrown building Home(dirty, state: _HomeState#6295a):
LateInitializationError: Field 'name' has not been initialized.

The relevant error-causing widget was:

This error occurs when you use a late variable before its initialization. You have to remember one thing, You have used some data or variables which are declared as "late" but their value is not changed or stored before using it. For example:

late String name;
@override
Widget build(BuildContext context) {
  return Scaffold(
        body: Text(name)
        //runtime error: 
        //LateInitializationError: Field 'name' has not been initialized.
  );
} 

Here, we have late String name; which means, the variable name has no value, its value will be initialized in the Future, and we have used this variable in Text()  widget without its initialization.

To solve this error, you must understand that there may be different Scenarios, but the reason is the same, the variable you are using is not initialized. In the above condition, we can solve by setting value in initState method, for example:

late String name;

@override
void initState() {
  name = "Flutter Campus";
  super.initState();
}
  
@override
Widget build(BuildContext context) {
  return Scaffold(
        body: Text(name)
  );
} 

Remember: You have to assign something to the late variable before using it.

You can also solve this issue by making "late" variable to nullable variable, for example:

String? name;

@override
Widget build(BuildContext context) {
  return Scaffold(
        body: Text(name??"") 
        //if "name" is null, the text will have empty
  );
} 

Here, we have created a nullable variable, which is assigned to the Text() widget, When you use Text(name!) null check operator instead shown like above, you may get "Null check operator used on a null value" Error. If you get this error, you can open the link to solve this error.

In this way, you can solve "LateInitializationError: Field has not been initialized" Error in Flutter

No any Comments on this Article


Please Wait...