Home > database >  How to move a function into a separate method?
How to move a function into a separate method?

Time:05-21

I have a function that is called when a ListTile is clicked. I need to move it to a separate method. The function is in onTap. I want to put it in a separate method outside of build. How can i do this?

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<EventListProvider>(
        builder: (context, listModel, child) {
          return ListView.builder(
            itemCount: listModel.eventList.length,
            itemBuilder: (context, index) {
              return Container(
                child: ListTile(
                    title: Text(
                      listModel.eventList[index].title,
                      style: const TextStyle(
                        color: Colors.black87,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    subtitle: Text(
                      listModel.eventList[index].detail,
                      style: const TextStyle(
                        color: Colors.black45,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onTap: () {
                      final event =
                          listModel.getEvent(listModel.eventList[index].id);
                      if (event != null) {
                        showModalBottomSheet<void>(
                          context: context,
                          builder: (BuildContext context) {
                            return EditEventBottomSheet(event: event);
                          },
                        );
                      }
                    }),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addEvent,
        child: const Icon(Icons.add),
      ),
    );
  }
}

CodePudding user response:

Method outside of build:

_onTap(int index, BuildContext context, ??? listModel) {
                  final event =
                      listModel.getEvent(listModel.eventList[index].id);
                  if (event != null) {
                    showModalBottomSheet<void>(
                      context: context,
                      builder: (BuildContext context) {
                        return EditEventBottomSheet(event: event);
                      },
                    );
                  }

In build method:

child: ListTile(
                // ...
                onTap: () => _onTap(index, context, listmodel),

You need to replace the ??? with the actual type of the listmodel variable, I could not see it in your code.

  • Related