Sobes.tech
Junior

What types of widgets are available in Flutter?

sobes.tech AI

Answer from AI

In Flutter, widgets are divided into two main categories:

  • StatelessWidget: Widgets whose state does not change after initial build. They describe a part of the UI that does not depend on any data at runtime.
  • StatefulWidget: Widgets with mutable state. They have an associated State object that contains mutable data and provides a mechanism to rebuild the widget when the state changes.

Additionally, widgets can be classified by their purpose:

  • Layout widgets: Manage the positioning of other widgets on the screen (e.g., Row, Column, Stack).
  • Material Components / Cupertino widgets: Provide ready-made UI elements that conform to Material Design (Android) or Cupertino (iOS) guidelines (e.g., AppBar, Button, TextField).
  • Input widgets: Allow user interaction with the app (e.g., TextField, Checkbox, Slider).
  • Interactive widgets: Respond to user gestures (e.g., GestureDetector, InkWell).
  • Painting & Effects widgets: Apply graphical effects (e.g., Opacity, ClipRRect).
  • Scrolling widgets: Enable content scrolling (e.g., ListView, GridView).

Widgets can be created in the following ways:

  • Primitive: Basic building blocks (e.g., Container, Text, Icon).
  • Composite: Made up of other widgets.
// Example of StatefulWidget
class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // Change state and trigger rebuild
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Counter:'),
        Text(
          '$_counter',
          style: Theme.of(context).textTheme.headline4,
        ),
        FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ],
    );
  }
}
// Example of StatelessWidget
class TitleWidget extends StatelessWidget {
  final String title;

  TitleWidget({required this.title});

  @override
  Widget build(BuildContext context) {
    return Text(
      title,
      style: TextStyle(fontSize: 24),
    );
  }
}
What types of widgets are available in Flutter… - sobes.tech