Middle
What are widget controllers used for in Flutter?
sobes.tech AI
Answer from AI
Widget controllers in Flutter are used to manage the state or behavior of a specific widget from outside, as well as to interact with it.
Main purposes of use:
- Programmatic control: Changing widget properties (e.g., scrolling a list, managing the cursor in a text field) without direct user interaction.
- Getting information: Reading the current state of a widget (e.g., current scroll position, entered text).
- Responding to events: Performing actions related to the widget in response to events elsewhere in the app.
Examples of popular controllers:
TextEditingController: Managing text fields (TextField,TextFormField). Allows getting and setting text, managing selection and cursor position.final myController = TextEditingController(); // Get text from the field final text = myController.text; // Set text in the field myController.text = 'New text';ScrollController: Managing scrollable widgets (ListView,GridView,SingleChildScrollView). Allows programmatic scrolling, getting current scroll position, and listening to scroll events.final myScrollController = ScrollController(); // Scroll to the beginning myScrollController.animateTo( 0, duration: Duration(milliseconds: 500), curve: Curves.easeOut, ); // Get current scroll position final position = myScrollController.position.pixels;PageController: Managing page widgets (PageView). Allows switching between pages, getting the current page, and listening to page change events.final myPageController = PageController(); // Move to the next page myPageController.nextPage( duration: Duration(milliseconds: 300), curve: Curves.easeIn, ); // Get current page final currentPage = myPageController.page;
Controllers are usually passed to the corresponding widget via its constructor. Managing the controller's lifecycle (creation and disposal) should occur in the widget that uses it, often in the initState method for creation and dispose for cleanup.
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late final TextEditingController _textController;
@override
void initState() {
super.initState();
_textController = TextEditingController();
}
@override
void dispose() {
_textController.dispose(); // Important to free resources
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _textController,
// ... other TextField properties
);
}
}
Using controllers allows explicitly separating the logic of widget management from its presentation.