Creating a custom controller in Flutter

Issue

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
InfiniteScroll(
  fetchMore: () async {}, // fetching more data
  builder: (data) {}, // building an item
)

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

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

Solution

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() {
    items.clear();
    notifyListeners();
  }
}

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

class InfiniteScroll extends StatefulWidget {
  InfiniteScroll({
    required this.controller
  });

  final InfiniteScrollController controller;

  @override
  State<StatefulWidget> createState() {
    return _InfiniteScrollState();
  }
}

class _InfiniteScrollState extends State<InfiniteScroll> {
  @override
  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: https://www.flutterclutter.dev/flutter/tutorials/create-a-controller-for-a-custom-widget/2021/2149/

Answered By – Schnodderbalken

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

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