I'm a beginner and I cannot understand one thing. So, I have these classes:
class Book {
int? id;
Author author = Author();
}
class Author {
String? firstName;
String? lastName;
}
Creating the book object in the widget
class MainWidget extends StatefulWidget {
const MainWidget({Key? key}) : super(key: key);
@override
State<MainWidget> createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
final Book myBook = Book();
@override
Widget build(BuildContext context) {
return ChangeBookAuthor(bookAuthor: myBook.author);
}
}
And changing the value of the author
First example
class ChangeBookAuthor extends StatefulWidget { final Author bookAuthor; const ChangeBookAuthor({Key? key, required this.bookAuthor}) : super(key: key); @override State<ChangeBookAuthor> createState() => _ChangeBookAuthorState(); } class _ChangeBookAuthorState extends State<ChangeBookAuthor> { late Author _bookAuthor; @override void initState() { _bookAuthor = widget.bookAuthor; super.initState(); } @override Widget build(BuildContext context) { return TextFormField( onChanged: (value) => _bookAuthor.firstName = value, ); } }Second example
class ChangeBookAuthor extends StatefulWidget { final Book book; const ChangeBookAuthor({Key? key, required this.book}) : super(key: key); @override State<ChangeBookAuthor> createState() => _ChangeBookAuthorState(); } class _ChangeBookAuthorState extends State<ChangeBookAuthor> { late Book _book; @override void initState() { _book = widget.book; super.initState(); } @override Widget build(BuildContext context) { return TextFormField( onChanged: (value) => _book.author.firstName = value, ); } }
In my application, I would like to have a ChangeBookAuthor widget that only gets the Author object and changes its value in the Book object in MainWidget. How can this be achieved? Why does the first example work and the second doesn't?