skip to Main Content

I’m learning Flutter.

Have this model class:

class TaskModel {
  String task;

  TaskModel({required this.task});
}

class TaskProvider extends ChangeNotifier {
  List<TaskModel> taskList = [];

  void addNotes(TaskModel userInput) {
    return taskList.add(userInput);
  }
}

When I press the button, the input in the text field should be added to taskList:

TextEditingController _controller = TextEditingController();
onPressed: () {
  context.read<TaskProvider>().addNotes(_controller.text);}

I get this error:

Error in ‘_controller.text’ The argument type ‘String’ can’t be assigned to the parameter type ‘TaskModel’

I need to find a way to convert to match that type

3

Answers


  1. change the add Task like this

    class TaskProvider extends ChangeNotifier {
      List<TaskModel> taskList = [];
    
      void addNotes(String userInput) {
        return taskList.add(TaskModel(task: userInput);
      }
    }
    
    

    Explanation:
    The error arises because you’re trying to pass a String (the text from the text field) to the addNotes function which expects a TaskModel object.

    Login or Signup to reply.
  2. your addNotes method expects a TaskModel object, but you are trying to add a string to your taskList

    class TaskModel {
              String task;
            
              TaskModel({required this.task});
            }
            
            
            class TaskProvider extends ChangeNotifier {
              List<TaskModel> taskList = [];
            
              void addNotes(TaskModel userInput) {
                return taskList.add(userInput);
               notifyListeners();
            
     }
    }
    
    
    TextEditingController _controller = TextEditingController();
    TextFormField(controller: _controller)
    
    
    
         onPressed:(){
        //validation - optional
            TaskModel taskModelObject = TaskModel(task:_controller.text);
            context.read<TaskProvider>().addNotes(taskModelObject);
            _controller.clear();
    }
    
    Login or Signup to reply.
  3. The data that needs to be added is TaskModel not a string, you should do this:

    addNotes(TaskModel(task:_controller.text))

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search