Creating a custom controller in Flutter


I created a widget named InfiniteScroll which handles asynchronously loaded data and renders it with ListView.builder. However I am having trouble creating a controller for it (for example for clearing all the loaded data). I read through the implementation of existing controllers such as TextEditingController but I can’t seem to wrap my head around it. Here’s an example of what I’m trying to achieve:

// I have
  fetchMore: () async {}, // fetching more data
  builder: (data) {}, // building an item

// need
  controller: _infiniteScrollController,
  fetchMore: () async {}, // fetching more data
  builder: (data) {} // building an item
// later

How to create such a controller? I am using flutter_hooks for local state management if that matters.


I don’t think the answer of @ValdaXD describes a good solution.

The way this is usually solved, also in native Flutter widgets like TextField or ScrollController is a controller class that extends ChangeNotifier.

The controller would handle the items and provide a public API to clear them:

class InfiniteScrollController extends ChangeNotifier {
  List<Widget> items = [];

  void clearItems() {

The widget could then display the items via the injected controller:

class InfiniteScroll extends StatefulWidget {
    required this.controller

  final InfiniteScrollController controller;

  State<StatefulWidget> createState() {
    return _InfiniteScrollState();

class _InfiniteScrollState extends State<InfiniteScroll> {
  Widget build(BuildContext context) {
    return ListView(
      children: widget.controller.items,

I have created a blog post with a different example but the same topic: a controller for a custom widget:

Answered By – Schnodderbalken

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *