DEV Community

Aadarsh Kunwar
Aadarsh Kunwar

Posted on

Flutter provides mainly 2 widgets Stateless and StatefulWidget

  1. Stateless Widget A Stateless widget is a widget that does not maintain any state. It is immutable, meaning that its properties cannot change after it is created. Stateless widgets are ideal for static content or UI elements that do not change.

Components:

StatelessWidget Class: Defines the widget's appearance based on the properties passed to it.
Common Uses:

Static content like text, icons, and images.
Widgets that do not depend on dynamic data.
Example:

`class MyStatelessWidget extends StatelessWidget {
  final String title;

  MyStatelessWidget({required this.title});

  @override
  Widget build(BuildContext context) {
    return Text(title);
  }
}`
Enter fullscreen mode Exit fullscreen mode
  1. Stateful Widget A Stateful widget is a widget that can change over time in response to user interactions or other factors. It has mutable state, meaning that it can store and manage data that can be updated dynamically. When the state of a Stateful widget changes, the framework automatically rebuilds the widget tree to reflect the changes.

Components:

StatefulWidget Class: Defines the widget's appearance and behavior.
State Class: Contains the mutable state for the widget. The State class is where the logic for updating the state resides.
Common Uses:

Interactive elements like forms, buttons, and animations.
Widgets that require user input or change based on external events.
Example:

`class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Counter: $_counter'),
        ElevatedButton(
          onPressed: _incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
Enter fullscreen mode Exit fullscreen mode


`

Top comments (0)