How to use Keys in Flutter to preserve the state?

How to use Keys in Flutter to preserve the state?

Keys are the ones to preserve state when widgets move around the widget tree. So, in this article, we will see how to use Keys in Flutter to preserve the state.

How to use Keys in Flutter to preserve the state?

We use Keys to preserve the user scroll location or keeping state when modifying a collection. If the entire widget subtree is stateless you don’t need a key. Now let see when to use the keys. We know that we use keys to preserve states when widgets move around the widget subtree. So, you don’t need keys in a stateless widget. But you will need a key in a Stateful widget.

To explain the keys let’s take a look at the below code in which tapping on the button will change the box’s colors. The keys store the value of the colors.  The following code is of the application created without the use of keys.

Stateless Widget Tree:

Here in this code, we have created the application using the stateless widget. We created a class PositionedTiles here. The comment you are seeing in this code is for the unique color to generate the colors for the boxes randomly. On tapping the button the swapTiles function gets activated. The onTap button is the smiley face at the bottom.

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MaterialApp(home: PositionedTiles()));

class PositionedTiles extends StatefulWidget{
@override
State<StatefulWidget> createState() => PositionedTilesState();
}

class PositionedTilesState extends State<PositionedTiles>{
late List<Widget> tiles;

@override
void initState(){
super.initState();
tiles = [
StatelessColorfulTile(),
StatelessColorfulTile(),
];
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Agency"),
backgroundColor: Colors.green,
) ,
body: SafeArea(child: Row(children: tiles)),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles),
);
}

swapTiles(){
setState(() {
tiles.insert(1, tiles.removeAt(0));
});
}
}

class StatelessColorfulTile extends StatelessWidget {
Color myColor = UniqueColorGenerator.getColor();
@override
Widget build(BuildContext context) {
return Container(
color: myColor, child: const Padding(padding: EdgeInsets.all(70.0)));
}
}

//this code snippet tells you how UniqueColorGenerator works
class UniqueColorGenerator {
static List colorOptions = [
Colors.blue,
Colors.red,
Colors.green,
Colors.yellow,
Colors.purple,
Colors.orange,
Colors.indigo,
Colors.amber,
Colors.black,
];
static Random random = Random();
static Color getColor() {
if (colorOptions.isNotEmpty) {
return colorOptions.removeAt(random.nextInt(colorOptions.length));
} else {
return Color.fromARGB(random.nextInt(256), random.nextInt(256),
random.nextInt(256), random.nextInt(256));
}
}
}

 

But when we will change it to the Stateful widget the code will work correctly but the application will show nothing. But as we use the keys here in the Stateful widget the application will work fine. The following code shown below is direct with the keys.

Stateful Widget Tree:

Here in this code, you can see we have used the keys feature here, because of which the application is working fine. The rest of the code is the same.

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MaterialApp(home: PositionedTiles()));

class PositionedTiles extends StatefulWidget{
@override
State<StatefulWidget> createState() => PositionedTilesState();
}

class PositionedTilesState extends State<PositionedTiles>{
late List<Widget> tiles;

@override
void initState(){
super.initState();
tiles = [
StatefulColorfulTile(key: UniqueKey()),
StatefulColorfulTile(key: UniqueKey()),
];
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Agency"),
backgroundColor: Colors.green,
) ,
body: SafeArea(child: Row(children: tiles)),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles),
);
}

swapTiles(){
setState(() {
tiles.insert(1, tiles.removeAt(0));
});
}
}

class StatefulColorfulTile extends StatefulWidget {
const StatefulColorfulTile({required Key key}) : super(key: key);
@override
State<StatefulWidget> createState() => StatefulColorfulTileState();
}
class StatefulColorfulTileState extends State<StatefulColorfulTile> {
late Color myColor;
@override
void initState() {
super.initState();
myColor = UniqueColorGenerator.getColor();
}
@override
Widget build(BuildContext context) {
return Container(
color: myColor,
child: const Padding(
padding: EdgeInsets.all(70.0),
));
}
}

class UniqueColorGenerator {
static List colorOptions = [
Colors.blue,
Colors.red,
Colors.green,
Colors.yellow,
Colors.purple,
Colors.orange,
Colors.indigo,
Colors.amber,
Colors.black,
];
static Random random = Random();
static Color getColor() {
if (colorOptions.isNotEmpty) {
return colorOptions.removeAt(random.nextInt(colorOptions.length));
} else {
return Color.fromARGB(random.nextInt(256), random.nextInt(256),
random.nextInt(256), random.nextInt(256));
}
}
}
how to use Keys in Flutter to preserve the state.
How to use Keys in Flutter to preserve the state.

Now it is clear from the above example where to add them. If you have to use the Stateful widget then you have to use the Keys. Now there are many types of Keys in a flutter. Following are the type of keys:

Types of keys in Flutter:

  • Value Key: The value key is used when it has to be assigned to something constant and extraordinary. For example, in the  To-Do List, the text entered is the value.
  • Object Key: The Object key is used when any single field such as name or birthday, maybe the same of more than two people but would be unique for each person or each data combination.
  • Unique Key: The unique key is used when there are many widgets with the same incentive then we must use define each widget as a unique widget. We used it in our code also because we didn’t know what random color would be assigned to it until the widgets were assembled.
  • Global key:  The use of Global key is that it contains the data which can be accessed by other widgets present in the code. In case you don’t want to share it with other widgets then you must use the Global Key<From State> that holds a form of state and won’t allow other widgets to access the data stored in it.

So, we can say that keys are a very good feature in a flutter. It only works with the Stateful widget. Also, the purpose is to use it to store the value of the current state when modifying the collection.

Conclusion:

Thanks for being with us on a Flutter Journey!

So, in this article, we have seen how to use Keys in Flutter to preserve the state. Also, feel free to comment and provide any other suggestions regarding Flutter tips & tricks.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide,  Flutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields