Home > Software engineering >  LateInitializationError: Field 'filterValue' has not been initialized
LateInitializationError: Field 'filterValue' has not been initialized

Time:11-19

I am very new to flutter, and fairly new to programming in general. I get this error message when I'm trying to run/debug my app. We're creating a ToDoList as a school project, and don't know what to do. Any help would be greatly appriciated!

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'EditTodoView.dart';
import 'TodoList.dart';
import 'model.dart';

class TodoListView extends StatefulWidget {
  const TodoListView({Key? key}) : super(key: key);

  @override
  _TodoListViewState createState() => _TodoListViewState();
}

class _TodoListViewState extends State<TodoListView> {
  final List<String> filteredAlternatives = ['All', 'Done', 'Undone'];
  late String filterValue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          "TIG169 TODO",
          style: TextStyle(color: Colors.black),
        ),
        actions: <Widget>[
          _todoFilter(),
        ],
      ),
      body: Consumer<MyState>(
        builder: (context, state, child) => TodoList(state.filter(filterValue)),
      ),
      floatingActionButton: _addTodoButton(context),
    );
  }

  Widget _todoFilter() {
    return PopupMenuButton<String>(
      onSelected: (String value) {
        setState(() {
          filterValue = value;
        });
      },
      itemBuilder: (BuildContext context) {
        return filteredAlternatives
            .map((filterAlternatives) => PopupMenuItem(
                value: filterAlternatives, child: Text(filterAlternatives)))
            .toList();
      },
      icon: const Icon(Icons.more_vert, size: 20, color: Colors.black),
    );
  }

  Widget _addTodoButton(BuildContext context) {
    return FloatingActionButton(
        backgroundColor: (Colors.grey),
        child: const Icon(Icons.add),
        onPressed: () async {
          var newTodo = await Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => EditTodoView(
                      Todo(
                        todoText: '',
                      ),
                    )),
          );
          if (newTodo != null) {
            Provider.of<MyState>(context, listen: false).addTodo(newTodo);
          }
        });
  }

  void whenComplete(Null Function() param0) {}
}

The error message i recieving when I try to debug it is:

Exception caught by widgets library 
The following LateError was thrown building Consumer<MyState>(dirty, dependencies: [_InheritedProviderScope<MyState?>]):
LateInitializationError: Field 'filterValue' has not been initialized.

The relevant error-causing widget was
Consumer<MyState>
package:firstapp/TodoListView.dart:32"

CodePudding user response:

Your problem is you are trying to use filterValue which, when is called, does not have a value yet. late keyword is like a "hack". It tells the program: "Don't worry if filterValue doesn't have a value right now, it will have when used!".

So as solution I would say either set a default value to filterValue and remove late keyword or ensure filterValue has a value before it's usage.

CodePudding user response:

late String filterValue;

This statement is causing problem for you because it has is been followed by late keyword. Late keyword allows you to initialize a variable "the first time it is read" instead of on its creation.

You should be able to fix this by giving it a default value and removing late keyword. Like this:

String filterValue = ""; (giving it a default value)

or you could make it nullable by adding a ? after data-type. But be careful as you may encounter 'called on null' errors by making it nullable, if not handled carefully. Like this:

String? filterValue; (making it nullable)

This way, the variable will be created during compile time instead of run time and LateInitializationError should disappear.

  • Related