Google News
logo
Flutter - Interview Questions
What is a StatelessWidget and how is it used in Flutter?
In Flutter, a `StatelessWidget` is a widget that represents an immutable part of the user interface. A `StatelessWidget` is created once when it is first inserted into the widget tree, and it does not change thereafter.

`StatelessWidget`s are used to display content that does not need to be updated dynamically. They are typically used for things like buttons, labels, icons, and other static UI elements that do not depend on external data or user input.

A `StatelessWidget` is implemented by creating a new class that extends the `StatelessWidget` class and overriding the `build()` method. The `build()` method is where the widget's appearance is defined, using other widgets or primitive drawing operations. Here's an example:
import 'package:flutter/material.dart';

class MyButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  MyButton({required this.text, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(text),
    );
  }
}​

In this example, we define a new `StatelessWidget` called `MyButton` that takes two required parameters: `text`, which specifies the text to display on the button, and `onPressed`, which specifies the function to call when the button is pressed.

In the `build()` method, we create an `ElevatedButton` widget that displays the `text` parameter and calls the `onPressed` function when the button is pressed.

`StatelessWidget`s are useful for creating simple, static UI elements that do not need to change over time. Since they are immutable, they are easy to reason about and optimize for performance. However, if you need to create a widget that can change over time, you should use a `StatefulWidget` instead.
Advertisement