Search code examples
performanceflutterbottom-sheet

Flutter modal bottom sheet performance issue


When dragging modal bottom sheets, the flutter application starts lagging if a lot of widgets live inside the sheet. This only occurs on the modal bottom sheet (showModalBottomSheet) and not on the normal one (showBottomSheet). Below I attached a screenshot of the performance analysis, which shows, that all widgets inside the sheet are beeing constantly rebuilt while the user is dragging.

I wrote a little demo to compare the performance of the two types of sheets. Is there a way to prevent the rebuilding while dragging?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "demo",
      home: Scaffold(
        body: MyButtons(),
      ),
    );
  }
}

class MyButtons extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              showModalBottomSheet<void>(
                context: context,
                builder: (context) => BottomSheet(),
              );
            },
            child: Text("show modal (laggy)"),
          ),
          RaisedButton(
            onPressed: () {
              showBottomSheet<void>(
                context: context,
                builder: (context) => BottomSheet(),
              );
            },
            child: Text("show normal (not laggy)"),
          ),
        ],
      ),
    );
  }
}

class BottomSheet extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 8.0,
      alignment: WrapAlignment.center,
      children: List<Widget>.generate(
        100,
        (int index) {
          return InputChip(
            label: Text("test"),
          );
        },
      ),
    );
  }
}


Solution

  • I have created this PR to fix this performance issue. The problem was that the AnimatedContainer from the ModalBottomSheet was not using the child property and therefore it was forcing to call builder method many times while animation is running instead of using the already built child widget.