Search code examples
flutterdartmobileflutter-widget

Stateless Vs Stateful rebuild


when a stateless widget is inside a stateful widget it will redraw or not? now the stateless widget can't be redrawn at run time but stateful can. the question is when the stateless widget is inside a stateful widget it will be redrawn or not?


Solution

  • A statelessWidget which is a child of a statefulWidget will be rebuilt if the statefulWidget rebuilds. Basically, when setState is called in a statefulWidget, the old state is chucked away and the build method runs with the new state. So if a statelessWidget it referenced in the statefulWidget's build method, yes it will be rebuilt.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        print('Stateful widget built');
        return Scaffold(
          appBar: AppBar(
            title: Text('Example'),
          ),
          body: BodyWidget(),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              setState(() {});
            },
            tooltip: 'Set state',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    
    class BodyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        print('Stateless widget built');
        return Container(
          child: Text('Stateless widget'),
        );
      }
    }
    

    Try this example out, when you hit the Fab, it re setState on the statefulWidget and you will get a print out in the console when each build method is run.