Google Flutter Basics 3 — Questions and Answers
Question 1: What is the key difference between StatelessWidget and StatefulWidget?
- StatefulWidget can rebuild with changing data, StatelessWidget cannot (Correct answer)
- StatelessWidget is faster to compile
- StatefulWidget cannot have children
- StatelessWidget requires a State object
Correct answer: StatefulWidget can rebuild with changing data, StatelessWidget cannot
StatefulWidget holds mutable state and can rebuild, while StatelessWidget is immutable.
Question 2: Which method must be overridden in a StatelessWidget?
- build() (Correct answer)
- createState()
- initState()
- render()
Correct answer: build()
A StatelessWidget must implement build() to describe its UI.
Question 3: Which method triggers a UI rebuild after state changes in a StatefulWidget?
- setState() (Correct answer)
- build()
- rebuild()
- update()
Correct answer: setState()
Calling setState() marks the widget dirty and schedules a rebuild.
Question 4: Which lifecycle method is called once when a State object is first created?
- initState() (Correct answer)
- build()
- dispose()
- didUpdateWidget()
Correct answer: initState()
initState() runs once when the State is inserted into the tree.
Question 5: Which method should be used to release resources like controllers?
- dispose() (Correct answer)
- deactivate()
- setState()
- initState()
Correct answer: dispose()
dispose() is called when the State is permanently removed, ideal for cleanup.
Question 6: Why are StatelessWidgets considered immutable?
- Their fields are final and cannot change after construction (Correct answer)
- They cannot be drawn on screen
- They have no build method
- They cannot accept parameters
Correct answer: Their fields are final and cannot change after construction
StatelessWidget properties are final, so the widget itself never changes.
Question 7: Where is mutable state stored for a StatefulWidget?
- In the associated State object (Correct answer)
- In the widget constructor
- In pubspec.yaml
- In the build context
Correct answer: In the associated State object
The State object holds mutable data that persists across rebuilds.
What is the key difference between StatelessWidget and StatefulWidget?