skip to Main Content

I’m building a Chat Page and want it to display the latest message when opened, similar to most chat apps. Currently, I have tried two approach.

Approach 1. Using addPostFrameCallback with jumpTo like this, but this will causes the screen flicker when opened.

WidgetsBinding.instance.addPostFrameCallback((_) {

  provider.chatScrollController.jumpTo(

  provider.chatScrollController.position.maxScrollExtent);

});

Approach 2. Using `reverse: true` but this will display the message at the bottom when there only one or two.

is there a better way to achieve smooth scrolling to the latest message without the flicker? Would love any advice or suggestions!

2

Answers


  1. You can use animateTo method from ScrollController. In your code change jumpTo to animateTo then add duration and curves properties inside the method like this:

    // Make sure the widget is already rendered.
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // Move the scroll position to the bottom of the page with animation.
      provider.chatScrollController.animateTo(
        provider.chatScrollController.position.maxScrollExtent,
        // [duration] for setting the animation duration. 
        duration: const Duration(seconds: 2),
        // [curve] An parametric animation easing curve, i.e. a mapping of the unit 
        // interval to the unit interval.
        // (https://api.flutter.dev/flutter/animation/Curve-class.html)
        // 
        // In simple term is to manage how your animation run.
        curve: Curves.fastEaseInToSlowEaseOut,
      );
    });
    

    This will animating your scroll to the bottom of the page.

    Reference animateTo Flutter Documentation

    Login or Signup to reply.
  2. You can achieve this by using a SingleChildScrollView with the reverse property set to true. Then, wrap it with an Align widget and set alignment: Alignment.bottomCenter, like so:

    body: SingleChildScrollView(
      reverse: true,
      child: Align(
        alignment: Alignment.bottomCenter,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            // Your widgets go here
          ],
        ),
      ),
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search