Stateful & Stateless Widget

Stateful and Stateless Widget

Introduction of Stateful and Stateless Widget

Stateful and Stateless widgets are the basic building blocks of the user interface, and understanding the difference between stateful and stateless widgets is crucial for building dynamic apps. Here’s a detailed look at both types of widgets, including their uses and how they behave.

1. Stateless Widget

A Stateless Widget is a widget that does not require mutable state. In other words, it does not change its properties during runtime. It’s suitable for the part of the UI that depends only on the configuration information in the widget itself and the BuildContext.

import 'package:flutter/material.dart';

class MyStatelessWidget extends StatelessWidget {
  final String title;

  const MyStatelessWidget({Key? key, required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Center(
        child: Text('This is a stateless widget'),
      ),
    );
  }
}

2. Stateful Widget

A Stateful Widget is designed to hold data that might change during the widget’s lifetime. Widgets that change state (like input forms, checkboxes, sliders, etc.) should be stateful. Stateful widgets maintain state in a State object, allowing them to keep state across builds.

import 'package:flutter/material.dart';

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key? key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Stateful Widget Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Text('$_counter', style: Theme.of(context).textTheme.headline4),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Conclusion

The choice between using a stateful and stateless widget depends on whether the part of the UI you are working on needs to be dynamic or static. Understanding the distinction and applying the right type of widget can greatly enhance the interactivity and performance of your Flutter apps.

Thank for visiting Hybrid App Development
Posted by Hussam HM

Premium Partner

WordPress Wallah offer's premium WordPress themes, plugins, and Template Kits free.

Details