user13295460
user13295460

Reputation:

Flutter access method of ViewModel into another ViewModel

i've a problem related to view models. I need to access the method of this viewModel:

class TheacerViewModel{
  Teacher _teacherX;

  TeacherViewModel(Teacher teacherX): _teacherX = teacherX;

  String get name{
    return _teacherX.name;
  }
  
  String get surname{
    return _teacherX.surname;
  }
  
  int get age{
    return _teacherX.age;
  }    
}

into this viewModel:

class CourseViewModel{
  Course _courseX;

  CourseViewModel(Course courseX): _courseX = courseX;

  String get subject{
    return _courseX.subject;
  }

    /*
    my solution (not working)
  Teacher get teacher{
    return _courseX.theacer;
  }
  */
}

My solution not working. It is possible to do this thing ?

I've already create Teacher and Course model.

Thanks.

for @towhid comment

now i have to update this part of code(maybe only the last line)and add "teacher: teacher" to CourseViewModel(...), but how ? because courses.map does not allow me to add 2 parameters.

List<CourseViewModel> coursesL = List<CourseViewModel>();

  void courses() async {
    List<Course> courses = await WebService().fetchCourses();
    notifyListeners();
    this.coursesL = courses.map((courseX) => CourseViewModel(courseX: courseX)).toList();

Upvotes: 1

Views: 1722

Answers (1)

towhid
towhid

Reputation: 3278

An ideal approach would be creating the independent ViewModel first and then pass that instance to the dependent ViewModels constructor to use its method and properties. This way, you can avoid of creating any unnecessary instances.

class CourseViewModel{
  Course _courseX;
  Teacher _teacher;

  CourseViewModel(Course courseX, Teacher teacher): _courseX = courseX, _teacher = teacher;

  String get subject{
    return _courseX.subject;
  }

  Teacher get teacher => _teacher;

}

Upvotes: 0

Related Questions