Google Flutter App Development 3 — Questions and Answers
Question 1: What is the key difference between StatelessWidget and StatefulWidget?
- StatelessWidget cannot have children
- StatefulWidget can rebuild when its mutable state changes (Correct answer)
- StatelessWidget renders faster always
- StatefulWidget cannot use build()
Correct answer: StatefulWidget can rebuild when its mutable state changes
StatefulWidget holds mutable state and rebuilds via setState, while StatelessWidget is immutable.
Question 2: Which method triggers a rebuild after changing state in a StatefulWidget?
- rebuild()
- setState() (Correct answer)
- notify()
- update()
Correct answer: setState()
Calling setState() marks the widget dirty and schedules a rebuild.
Question 3: Where should you typically dispose of controllers like AnimationController?
- In build()
- In the dispose() method of the State (Correct answer)
- In initState()
- In the constructor
Correct answer: In the dispose() method of the State
dispose() releases resources when the State object is permanently removed.
Question 4: Which lifecycle method runs once when a State object is first created?
- build()
- initState() (Correct answer)
- didUpdateWidget()
- dispose()
Correct answer: initState()
initState() is called once when the State is inserted into the tree.
Question 5: What is a BuildContext primarily used for?
- Storing app data
- Locating a widget's position in the tree to access inherited widgets (Correct answer)
- Running network requests
- Compiling Dart code
Correct answer: Locating a widget's position in the tree to access inherited widgets
BuildContext represents a widget's location in the tree and is used to look up ancestors like Theme or Navigator.
Question 6: Why are most Flutter widgets immutable?
- To save memory only
- So the framework can efficiently rebuild and diff the tree (Correct answer)
- Because Dart forbids mutation
- To avoid using state
Correct answer: So the framework can efficiently rebuild and diff the tree
Immutable widgets let Flutter cheaply rebuild and reconcile the widget tree.
Question 7: What does the 'const' keyword on a widget constructor enable?
- Faster network calls
- Compile-time constant widgets that Flutter can skip rebuilding (Correct answer)
- Automatic state management
- Larger app size
Correct answer: Compile-time constant widgets that Flutter can skip rebuilding
const widgets are canonicalized at compile time and can be reused without rebuilding.
What is the key difference between StatelessWidget and StatefulWidget?