Advertisements
Flutter Stateless and Stateful Widgets
In flutter, the views are updated based on state.
Stateless widgets
These widgets doesn't change after they are built. So, they are called stateless widgets. Static texts, static icons are some of the stateless widgets.
Following is a sample code for stateless widgets.
import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Hello Rainbow Rectangle'), ), body: HelloRect(), ), ), ); } class HelloRect extends StatelessWidget { @override Widget build(BuildContext context) { return const Center( child: Text( "Hello!", style: TextStyle(fontSize: 40), ), ); } }
Lets next see an example for Stateful widget.
In stateful widget, the widget should extend class StatefulWidget and there should be set createState method where the state class is instantiated.
The class _HelloRectangleState is the state class and it has the build method for building the widget UI, necessary state variables and methods. Since we use a button here, a method for button action _generateRandomColor is added.
You can see a setState method being called in the button action, this is used to refresh the stateful widget. The setState method will update all the sub views in the hierarchy and the stateless sub views are unaffected.
import 'dart:math'; import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Hello Rainbow Rectangle'), ), body: HelloRectangle(text: 'Hello from instantiation!'), ), ), ); } class HelloRectangle extends StatefulWidget { final String text; HelloRectangle({ required this.text, }); @override createState() => _HelloRectangleState(); } class _HelloRectangleState extends State<HelloRectangle> { Color _color = Colors.greenAccent; void _generateRandomColor() { var random = Random(); setState(() { _color = Color.fromARGB( 255, random.nextInt(255), random.nextInt(255), random.nextInt(255), ); }); } Widget build(BuildContext context) { return Center( child: TextButton( onPressed: _generateRandomColor, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(_color), ), child: Center( child: Text( widget.text, style: TextStyle(fontSize: 40.0, color:Colors.black), textAlign: TextAlign.center, ), ), ), ); } }