Simple stateless widget in Flutter
A stateless widget is a widget that doesn't require a State object. They are useful when the widget doesn't need to interact with the user, doesn't need to change over time, and is the same every time it's built. In this article, we'll learn how to create a simple stateless widget in Flutter. We'll also learn how to pass data to a stateless widget.
import 'package:flutter/material.dart'
class WidgetName extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App title',
home: Container(
child: Text('Hello World'),
),
);
}
}
This is a simple code snippet for creating a Stateless widget in Flutter. As you know that we can create two types of widgets in Flutter - Stateless Widgets and Stateful widgets.
To create a stateless widget in Flutter, first, we import package 'package:flutter/material.dart' it means you can use inbuilt flutter widgets in your app. Then we create a class with class name 'WidgetName'. You can change it as per your requirement. Now we extend StatelessWidget class in our class sp that you can return your layout as a widget.
Now we override the build() function by using the @override keyword above it and return the widget layout. We are using MaterialApp as a parent component that has 'title' and 'home' params where we can structure the widget.
Pass data to Stateless Widget
In order to pass data to a stateless widget in Flutter, you need to create a constructor for the widget that accepts the data as a parameter. The data can then be used within the widget by referencing the parameter.
class FirstScreen extends StatelessWidget {
const FirstScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("First Screen"),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SecondScreen(
title: 'Second Screen',
description: 'Second Screen Description',
),
),
);
},
child: const Text('Go to Second Screen'),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({Key? key, required this.title, required this.description}) : super(key: key);
final String title;
final String description;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(description),
),
);
}
}
- Pass Data to Stateless Widget in Flutter
- Add border to widget in Flutter
- Create stateful widget in Flutter
- Add a single widget as a sliver in Flutter
- Center Row widget children vertically and horizontally Flutter
- Add spacing between characters of Text widget Flutter
- Convert text of Text widget to uppercase or lowercase in Flutter