'How to navigate to next ListView item in flutter

I want to navigate to the next item on a Listview.

I tried implementing the solution in this post but it doesn't work for me.

I created a function nextLesson() to implement the logic of moving to the next item and referenced the function in the onPressed parameter of the button.

What am I missing?

Here is my code.

class LessonDetailScreen extends StatefulWidget {
  static const routeName = '/lesson-detail';
  Lesson? currrentLesson;
  LessonDetailScreen({this.currrentLesson});

  @override
  State<LessonDetailScreen> createState() => _LessonDetailScreenState();
}

class _LessonDetailScreenState extends State<LessonDetailScreen> {

  @override
  Widget build(BuildContext context) {
    final lessonId = ModalRoute.of(context)!.settings.arguments as String;
    var loadedLesson = Provider.of<Lesson>(context).findById(lessonId);

    void nextLesson() {
      setState(() {
        int currentIndex = loadedLesson.lessons.indexOf(loadedLesson);
        if(currentIndex >= loadedLesson.lessons.length || loadedLesson.lessons.isEmpty) return;
        var nextLesson = loadedLesson.lessons[currentIndex + 1];
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (ctx) => LessonDetailScreen(
              currrentLesson: nextLesson,
            ),
          ),
        );
      });
    }

    return TextButton.icon(
              label: Text(
                'Next Lesson',
                style: TextStyle(fontSize: 20),
              ),
              style: ButtonStyle(),
              onPressed: nextLesson,
              icon: Icon(
                Icons.arrow_forward,
                size: 50,
                color: Colors.green,
              ),
            );
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source