Home > Software engineering >  Widget rebuilding even after passing the same key
Widget rebuilding even after passing the same key

Time:10-31

Minimal reproducible code:

class MainScreen extends StatefulWidget {
  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(onPressed: () => setState(() {})),
      body: FooPage(key: ValueKey(0)),
    );
  }
}

class FooPage extends StatelessWidget {
  FooPage({super.key});
  final int _number = math.Random().nextInt(100);

  @override
  Widget build(BuildContext context) {
    print('number = $_number');
    return Container();
  }
}

Each time you click the FAB, the number prints a new value. But as I'm already passing same key to the FooPage, why is it the MainScreen creates a new FooPage instance from scratch instead of using the existing one (with key 0)?


NOTE:

Please don't post answers to use const FooPage() after declaring a const constructor in the FooPage or assign FooPage to a final instance field in the MainScreen etc.

CodePudding user response:

Adding a key to a StatelessWidget doesn't make it stateful (remebering the random int).

I.e. the framework will still dispose and rebuild it as a new instance when deemed necessary.

  • Related