Home Blog Page 6

How to Make a Flutter Quiz App | Step-by-step App Guide in 2023

0
Flutter Quiz App | Step-by-step App Guide

In this guide, we’ll find out about the simple yet elegant Flutter Quiz App. 

Additionally, we learn about a few of the plugins and widgets, along with their features, prerequisites, and setup instructions.

This Flutter Quiz App Widgets and Plugins

The features or modules listed below will be included in this app:

  • Ten multiple-choice questions, with room for more.
  • Each question has four button-based selectable options, with the exception of the final one.
  • Each question’s score will be determined by the option that was chosen (internally).
  • Additionally, in addition to the score and restart button, a comment based on the final score will be displayed at the end of this flutter quiz app.
  • There are two screens in the app: the home screen (where questions will be displayed) and the result screen (where scores and remarks will be displayed).
  • Specifically, the main.dart, question.dart, answer.dart, quiz.dart, and result.dart modules will be used to organize the entire app.

You can review the fundamentals of flutter and dart by creating this app. 

Concepts

We will be discussing many ideas, including:

  • Displaying widgets on the screen.
  • Widget recycling
  • Snackbar
  • Shared Preferences
  • Internal Logic
  • Files
  • FutureBuilder
  • Builder
  • Row
  • Changing the screen.
  • TextFormField
  • Columns
  • Buttons etc.

We must first create a flutter project to make a Flutter Quiz App firebase, which will provide us with numerous files and folders, in order to begin developing the app. An existing main.dart file can be found in the Lib folder. 

Currently, four files need to be created in the same folder rest: 

  1. question.dart
  2. answer.dart
  3. quiz.dart
  4. result.dart

Requirements

Read on to learn what is needed:

  • Flutter
  • Android Studio or VS Code
  • Both editors need the installation of the Flutter and Dart plugins.

The First Step to Creating a Flutter Quiz App

The best way to make a stunning Flutter quiz app firebase. The question model, which has a list of possible answers and a text to display its title, is what we will make first.

Creating the Questions Page

  1. The number of current questions out of all the questions will be displayed in a text box first. Therefore, we need to initialize the question number variable to 1. 
  2. We will then have a page view where each of our questions will be displayed individually. 
  3. The page view’s default scoring behavior should be disabled. The length of our questions array will then be the number of items on the page view. 
  4. Based on the current question, we will create our question UI inside the item builder. 
  5. As a result, we will have a text to display the question title here in the build question method, and an option’s widget to display the options based on the current question.
import 'package:flutter/material.dart';

import './quiz.dart';
import './result.dart';

void main() => runApp(const MyApp());

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

@override
State<StatefulWidget> createState() {
	return _MyAppState();
}
}

class _MyAppState extends State<MyApp> {
final _questions = const [
	{
	'questionText': 'Q1. Who created Flutter?',
	'answers': [
		{'text': 'Facebook', 'score': -2},
		{'text': 'Adobe', 'score': -2},
		{'text': 'Google', 'score': 10},
		{'text': 'Microsoft', 'score': -2},
	],
	},
	{
	'questionText': 'Q2. What is Flutter?',
	'answers': [
		{'text': 'Android Development Kit', 'score': -2},
		{'text': 'IOS Development Kit', 'score': -2},
		{'text': 'Web Development Kit', 'score': -2},
		{
		'text':
			'SDK to build beautiful IOS, Android, Web & Desktop Native Apps',
		'score': 10
		},
	],
	},
	{
	'questionText': ' Q3. Which programing language is used by Flutter',
	'answers': [
		{'text': 'Ruby', 'score': -2},
		{'text': 'Dart', 'score': 10},
		{'text': 'C++', 'score': -2},
		{'text': 'Kotlin', 'score': -2},
	],
	},
	{
	'questionText': 'Q4. Who created Dart programing language?',
	'answers': [
		{'text': 'Lars Bak and Kasper Lund', 'score': 10},
		{'text': 'Brendan Eich', 'score': -2},
		{'text': 'Bjarne Stroustrup', 'score': -2},
		{'text': 'Jeremy Ashkenas', 'score': -2},
	],
	},
	{
	'questionText':
		'Q5. Is Flutter for Web and Desktop available in stable version?',
	'answers': [
		{
		'text': 'Yes',
		'score': -2,
		},
		{'text': 'No', 'score': 10},
	],
	},
];

var _questionIndex = 0;
var _totalScore = 0;

void _resetQuiz() {
	setState(() {
	_questionIndex = 0;
	_totalScore = 0;
	});
}

void _answerQuestion(int score) {
	_totalScore += score;

	setState(() {
	_questionIndex = _questionIndex + 1;
	});
	// ignore: avoid_print
	print(_questionIndex);
	if (_questionIndex < _questions.length) {
	// ignore: avoid_print
	print('We have more questions!');
	} else {
	// ignore: avoid_print
	print('No more questions!');
	}
}

@override
Widget build(BuildContext context) {
	return MaterialApp(
	home: Scaffold(
		appBar: AppBar(
		title: const Text('Geeks for Geeks'),
		backgroundColor: const Color(0xFF00E676),
		),
		body: Padding(
		padding: const EdgeInsets.all(30.0),
		child: _questionIndex < _questions.length
			? Quiz(
				answerQuestion: _answerQuestion,
				questionIndex: _questionIndex,
				questions: _questions,
				) //Quiz
			: Result(_totalScore, _resetQuiz),
		), //Padding
	), //Scaffold
	debugShowCheckedModeBanner: false,
	); //MaterialApp
}
}

This quiz.dart file, which makes use of the class Question, has already been imported. The class question would be stateless, just like this flutter quiz app, so it wouldn’t need to change throughout the run cycle. Following the widget tree, which provides the structure for the Question widget, comes the constructor Question.

People, who read this article also read: Flutter Liquid Swipe Animation

Creating the Options Page

  1. A column that we can map to the options of the questions is present inside our options widget, allowing us to compile a list of options. As a result, a text is created inside the build option method to display the options.
  2. Now that they are decorated, we can add some space, padding, and margin to make it more clickable while also viewing the background color. 
  3. Now that we have checked to see if the question is locked, we do nothing.
  4. If not, we lock the question and choose the answers the user chose.
  5. So now all we have to do is call a new method, get the caller information for our option, and then add the option to the inside of the question. 
  6. We’ll choose the color for the container’s border and the symbols for the right and wrong answers.
import 'package:flutter/material.dart';

import './answer.dart';
import './question.dart';

class Quiz extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function answerQuestion;

const Quiz({
	Key? key,
	required this.questions,
	required this.answerQuestion,
	required this.questionIndex,
}) : super(key: key);

@override
Widget build(BuildContext context) {
	return Column(
	children: [
		Question(
		questions[questionIndex]['questionText'].toString(),
		), //Question
		...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
			.map((answer) {
		return Answer(
			() => answerQuestion(answer['score']), answer['text'].toString());
		}).toList()
	],
	); //Column
}
}
import 'package:flutter/material.dart';

class Question extends StatelessWidget {
final String questionText;

const Question(this.questionText, {Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
	return Container(
	width: double.infinity,
	margin: const EdgeInsets.all(10),
	child: Text(
		questionText,
		style: const TextStyle(fontSize: 28),
		textAlign: TextAlign.center,
	), //Text
	); //Contaier
}
}

Creating the Correct Answer Calculator

  1. How many questions the user correctly answered will be counted. 
  2. To check if the number of questions is less than the total question, we will now create a button method. 
  3. The number of the subsequent questions will be raised by one inside the city-state.
  4. Currently, we must create and initialize a page controller. 
  5. Following that, we will add a new score variable to our options widget. 
  6. The score will be raised by 1 after we determine whether the chosen option is accurate. 
  7. The button must now only be visible after the user has chosen an option. 
  8. As a result, we will create an islocked variable and set its initial value to false. 
  9. Next, we’ll set the value of the question status variable inside the options widget. 
  10. The islocked status is then changed to false inside the elevated button in preparation for the following query. Now, we only display the button here if the question is locked; otherwise, nothing.
import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
final Function selectHandler;
final String answerText;

const Answer(this.selectHandler, this.answerText, {Key? key})
	: super(key: key);

@override
Widget build(BuildContext context) {
	// use SizedBox for white space instead of Container
	return SizedBox(
	width: double.infinity,
	child: ElevatedButton(
		onPressed: selectHandler(),
		style: ButtonStyle(
			textStyle:
				MaterialStateProperty.all(const TextStyle(color: Colors.white)),
			backgroundColor: MaterialStateProperty.all(Colors.green)),
		child: Text(answerText),
	),
	); //Container
}
}

This answer.dart file was also imported into the quiz.dart file. The answer.dart file was also added to the quiz.dart file. The Answer class that was used in the quiz.dart file is contained in this file. Answers would also be stateless, similarly to quizzes and question classes. SelectHandelr and the string answerText have been passed into the class Answer function using the keyword final because they are stateful widget components and must be specified immutably as a result. Failing to do so will result in a dart analysis warning. That is followed by the constructor and the usual widget tree to give it a structure.

Creating the Result Page for Flutter Quiz App

  1. The result page must be visited if we get to the final question. 
  2. Consequently, we visit the results page and run the score to see how many questions the user got correct.
  3. The See Result Button will appear here when we choose any of the options. 
  4. It will take us to the results page once we click it.. 
  5. We can design our results page and finally obtain the grade here. 
// ignore_for_file: avoid_print

import 'package:flutter/material.dart';

class Result extends StatelessWidget {
final int resultScore;
final Function resetHandler;

const Result(this.resultScore, this.resetHandler, {Key? key})
	: super(key: key);

//Remark Logic
String get resultPhrase {
	String resultText;
	if (resultScore >= 41) {
	resultText = 'You are awesome!';
	print(resultScore);
	} else if (resultScore >= 31) {
	resultText = 'Pretty likeable!';
	print(resultScore);
	} else if (resultScore >= 21) {
	resultText = 'You need to work more!';
	} else if (resultScore >= 1) {
	resultText = 'You need to work hard!';
	} else {
	resultText = 'This is a poor score!';
	print(resultScore);
	}
	return resultText;
}

@override
Widget build(BuildContext context) {
	return Center(
	child: Column(
		mainAxisAlignment: MainAxisAlignment.center,
		children: <Widget>[
		Text(
			resultPhrase,
			style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
			textAlign: TextAlign.center,
		), //Text
		Text(
			'Score ' '$resultScore',
			style: const TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
			textAlign: TextAlign.center,
		), //Text
		TextButton(
			onPressed: resetHandler(),
			child: Container(
			color: Colors.green,
			padding: const EdgeInsets.all(14),
			child: const Text(
				'Restart Quiz',
				style: TextStyle(color: Colors.blue),
			),
			),
		),
		], //<Widget>[]
	), //Column
	); //Center
}
}

OUTPUT

Conclusion

We learned how to create the Flutter Quiz App in this tutorial. Additionally, using real-world examples, we looked at how to modify options, make new pages, and provide icons when hovered or clicked. In the end, we discovered how to create a Flutter Quiz App from a single location.

Would you like to check other interesting Flutter tutorials?

Flutter Liquid Swipe Animation – The Best Liquid Swipe Animation in 2023

0
Flutter Swipe Animation | The Best Liquid Swipe Animation

How do you make a flutter liquid swipe animation? We’ll demonstrate how to incorporate a liquid Swipe animation into your Flutter application using a demo program. The Liquid Swipe animation was impressive and was created for the Android, iOS, and React Native platforms.

Flutter Liquid Swipe Animation 

A screen movement known as Liquid Swipe animation has the appearance of moving water. Most of the time, these animations have a moderate, fluid development that might wave or repeat patterns. (Additionally, the need for realistic-feeling liquid swipe animation is what makes it work.) Liquid swipe animation may create results as a floating state or swiping action.

Requirements

  • Flutter
  • Android Studio or VS Code
  • Both editors need the installation of the Flutter and Dart plugins.

Widgets Used

Since iOS, Android, and web-enabled devices can effectively utilize the strategy, it has actually started to explode in popularity. We will require the liquid_swipe package for this animation. Liquid Swipe is a New Page that Unveils Liquid Animation.

  1. Row Widget
  2. Liquid Swipe Widget
  3. Stack Widget
  4. Button Widget
  5. Positioned Widget
  6. Image Widget
  7. Icon Widget

People, who read this article also read: Flutter LayoutBuilder Widget Example Step by Step

Creating a Flutter Swiper Animation

Simply use the liquid swipe package and within the page’s property. 

  • We add some colored containers with this.
  • We can swipe horizontally between the container pages. 
  • Optionally set both these properties to have a side reveal bar on the right side.
  • Next, we wrap a stack widget around the liquid swipe widget. 
  • After the liquid swipe widget, we add a position widget with this. 
  • We position a row widget with two text buttons.
  • At the bottom of the screen to add some functionality to these buttons we add a controller within the liquid swipe widget that we initialize within the state.
  • Next, we use this controller to implement the functionality of the skip and also of the next button with this. 
  • If I click on the next button then we go to the next page and if we click on the skip button then we go directly to the last page.
  • Also between both text buttons, you can add a dot indicator that comes from the smooth page indicator package. 
  • With this, we can tap on the different dots to navigate between the pages or if we basically swipe between the pages then you see the progress in this dot indicator. 

Make sure to also add this callback to make the dot indicator work and finally we replace the container widgets with real page.

Example how to create a flutter liquid swipe animation

Step 1: Use the command to create a Flutter app:

flutter create liquid_swipe

Step 2: Make a file in both main.dart and home.dart to write code.

Step 3: Incorporate the liquid_swipe dependency using the code found in main.dart:

import 'package:liquid_swipe/liquid_swipe.dart';
import 'package:flutter/src/material/icons.dart';

Step 4: Add the requirement to your pubspec.yaml file as displayed below:

version: 1.0.011

environment:

sdk: ">=2.7.0 <3.0.0"

dependencies:

flutter:

sdk: flutter

# The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for ios style icons. cupertino icons: 0.1.3

liquid swipe: 1.5.0

Step 5:

Establish dependencies on pubspec.yaml

liquid_swipe: ^2.1.1

Get the package from Pub:

flutter packages get

Incorporating the attributes together

Step 5: As shown below, we must add the following attributes to the LiquidSwipe() method: pages, fullTransitionValue, waveType, positionSlideIcon, and enableSlideIcon.

body:LiquidSwipe(
   pages: page,
 enableLoop: true,
 fullTransitionValue: 300,
 enableSlideIcon: true,
 waveType: WaveType.liquidReveal,
 positionSlideIcon: 0.5,
),

With any widget as an argument, the main() function in the main.dart file calls runApp() to create the layout. We have a stateful class (mutable class) called MyliquidSwipe() with the following home:

import 'package:flutter/material.dart';
import './liquid_swipe.dart';
void main() {
runApp(
	MaterialApp(
	
		title: "My Ani",
		home: MyliquidSwipe(),
		),
	);
	}

Step 6: In the assets folder, we will add images. You can add there any images you require to be displayed. Activate assets in pubspec.yaml file as shown below:

assets:
- assets/

The Complete Source Code:

import 'package:flutter/material.dart';
import 'package:liquid_swipe/liquid_swipe.dart';
import 'package:flutter/src/material/icons.dart';
class MyliquidSwipe extends StatelessWidget {

@override
Widget build(BuildContext context) {
final page = [
	Container(
	color:Colors.brown,
	child: Padding(
		padding: const EdgeInsets.all(100.0),
		child: Center(
		child: Column(
			children:<Widget>[
				
			Text("Welcome To GeeksforGeeks",style:TextStyle(
			fontSize: 30,
			color:Colors.green[600],
			),
			),
		
			]
		),
		),
	),),
Container(color:Colors.yellow[100],
child: Padding(
	padding: const EdgeInsets.all(120.0),
	child: Center(
		child: Column(
			children:<Widget>[
			Image.asset("assets/save.png"),
			Text("",style:TextStyle(
			fontSize: 20,
			color:Colors.green,
			),
			)
			]
	),),
),),

Container(color: Colors.blue[100],
child: Padding(
	padding: const EdgeInsets.all(100.0),
	child: Center(
		child: Column(
			children:<Widget>[
			
			Text(" GeeksforGeeks A Computer Science portal
					for geeks",
			style:TextStyle(
			fontSize:30 ,
			color:Colors.green[600],
			),
			),
	]),),
))];
	return Scaffold(
	body: LiquidSwipe(
		enableLoop: false,
		pages: page,
		slideIconWidget: Icon(Icons.arrow_back_ios),
	),
	);
}
}

Output:

flutter liquid swipe animations

Conclusion

We learned how to create Flutter Liquid Swipe Animation in this tutorial. Additionally, using real-world examples, we looked at how to modify options, make new pages, and provide icons when hovered or clicked. In the end, we discovered how to create a Flutter Liquid Swipe Animation from a single location.

People who read this article also read: How to Use the Flutter Positioned Widget?

Flutter SizedBox Widget Example – Step by Step Guide in 2023

0
Flutter-SizedBox--Life-Changing-Beginners-Guide

Flutter SizedBox widget is what we know as a box with a specific size. Now, let’s learn it in depth.

What is Flutter SizedBox?

Flutter SizedBox, unlike Container, does not support color or decoration. The widget is only used to resize the widget supplied as a parameter. The default constructor and certain named constructors are used in the examples below.

How the Flutter SizedBox help to Align

It’s a box widget in which we specify the size of the box.

  1. If the child widget has no height or width, we must provide the SizedBox widget the dimension.
  2. Now, If we leave the height and width parameters blank, it will use the child’s height and width as its dimensions. If the child’s size is determined by its parent’s size, the height and width must be specified.
  3. SizedBox will try to size itself as near to the supplied height and width as feasible given the parent’s limitations if it is not given a child. If the height or width is null or undefined, it is assumed to be zero.

If the width or height are both null, this widget will try to scale itself to match the child’s size in that dimension. 

People, who read this article also read: Flutter LayoutBuilder Widget Example Step by Step

SizedBox Widget has the following properties:

  • child: This property accepts a child widget as an object and displays it beneath the SizedBox in the widget tree or within the SizedBox on the screen.
  • height: The height of SizedBox in pixels is specified by this attribute. It has the same value as the object.
  • width: This property likewise has a double value as the object to provide the SizedBox width.
  • key: This key is for the widget.

Flutter SizedBox Vs. Container

Containers may also be utilized to provide separation between widgets. Alternatively, cover the child and give it a certain height.

However, Container has several unique qualities.

So, instead, we may use SizedBox, which allows us to define the child, height, and width. However, it functions similarly.

Also, because Container has more attributes, it is a heavier widget, and you may make the SizedBox widget constant. This improves efficiency.

Why is the Flutter SizedBox in use?

This widget, when given a child, compels it to have a particular width and/or height. If the parent of this widget does not allow them, these settings will be ignored. This occurs, for example, when the parent is a screen (which compels the child to be the same size as the parent) or another SizedBox (which forces its child to have a specified width and/or height). This may be fixed by enclosing the child SizedBox in a widget that allows it to be any size up to the parent’s size, such as Center or Align.

The Expand Constructor SizedBox

The expand constructor may be used to create a SizedBox that expands to accommodate the parent. It is the same as doubling the width and height.

How to Make Use of the SizedBox Widget

  1. Allow space between widgets
  2. Modify the Widget Size

Allow space between widgets.

As previously stated, SizedBox is utilized to provide space between widgets.

const SizedBox(height: 20), //Add space Vertically
const SizedBox(width: 20), //Add Space Horizontally

Modify the Widget Size

We specify the SizedBox’s height and width. It will disregard the child widget’s width and height and give it a custom width and height.

SizedBox(
            height: 20,     //This become the height of the container
            child: Container(
              height: 100,    //This height will be ignored
              color: Colors.red,
            ),
      ),

Output:

flutter sizedbox

If we use double.infinity() as the height or width of the flutter SizedBox widget, it will occupy the parent widget’s whole width or height.

Scaffold(
      body: SizedBox(
        height: double.infinity, // This will take the whole space
        width: double.infinity,
        child: Container(
          height: 100,
          color: Colors.red,
        ),
      ),
    );

Output:

flutter sizedbox

Constructors of SizedBox

Name constructors for SizedBox are as follows:

  1. SizedBox.fromSize()
  2. SizedBox.expand()
  3. SizedBox.shrink()

SizedBox.fromSize()

The Size() object is used to create a SizedBox widget. The Size() Object will be sent to this constructor.

SizedBox.fromSize(
            size: const Size(100, 150), //(width, height)
            child: Container(
              height: 100,
              color: Colors.red,
            ),
          ),

Output:

flutter sizedbox from size

What exactly is Size()?

It’s from the dart user interface. When working with media queries. The size of the device may be obtained from the media query by utilizing. 

We may also pass width and height through it.

Size() width and height are therefore used by the SizedBox widget to generate flutter UI.

Instead of passing the height and width to the SizedBox, we now use Size ().

People, who read this article also read: How to Use the Flutter Positioned Widget?

Where SizedBox.fromSize() comes in handy.

SizedBox.expand()

This constructor can also be used to expand the child to an unlimited width and height, allowing it to fill all available space.

Scaffold(
     
      body: SizedBox.expand( //Behave just like double.infinity height and width
        child: Container(
          height: 100,
          color: Colors.red,
        ),
      ),
    );

SizedBox inside the Column Widget

When we set the double.infinity width to the SizedBox inside the Column widget. It will take up the entire available screen area.

Height and width are both infinite

Column(
        children: [
          SizedBox(
            width: double.infinity, // Take whole horizontal space
            child: Container(
              height: 100,
              color: Colors.red,
            ),
          ),
        ],
      ),

Output:

flutter sizedbox column

Exception Error

However, if we set the double.infinity to the SizedBox widget’s height property. It will not occupy the entire vertical area on the screen. Keep it in mind! (In this case, Column BoxConstraints compels an unlimited height.)

Solution

Simply utilize the Expanded widget to Make SizedBox to take up the whole height of the screen.

Previously 

Column(
        children: [
          SizedBox(
            height: double.infinity, //Inside column this will produce error
            child: Container(
              height: 100,
              color: Colors.red,
            ), 
          ),
        ],
      ),

Now 

Column(
        children: [
	          Expanded(           //This will solve the problem
            child: SizedBox(
              height: double.infinity,
              child: Container(
                height: 100,
                color: Colors.red,
              ),
            ),
          ),
        ],
      ),

SizedBox.shrink()

This constructor serves to reduce the size of everything inside the SizedBox. But the question is, how can we put it to use?

SizedBox.shrink(
            child: Container(
              height: 300,
              color: Colors.red,
            ),
          ),

We utilize SizedBox with ConstrainedBox widgets constraints property and assign BoxConstraints to determine the minimum height and width.

Invisible Object SizedBox

SizedBox is invisible by default. That is why we use it to represent space. Consider Container Widget if you wish to colorize the box.

Padding with SizedBox

Consider the following example.

AppBar(
        title: const Text('MY PAGE'),
        actions: [
          IconButton(
            onPressed: () {},
            icon: const Icon(Icons.search),
          ),
          const SizedBox(
            width: 20,   //Here Sized Box will add some padding after search icon
          )
        ],
      )

Output:

flutter appbar sizedbox search

ListView with Flutter SizedBox

Let’s look at how SizedBox may increase space to a ListView.

ListView(
        children: const [
          Text('First Widget'),
          SizedBox(height: 20),
          Text('Second Widget')
        ],
      ),

Row Widget with Flutter SizedBox

SizedBox may also serve inside the Row widget as well.

Row(
        children: const [
          Text('First Widget'),
          SizedBox(width: 20), //Add horizontal space
          Text('Second Widget')
        ],
      ),

Sized Boxes in Flutter 

There are additional widgets in Flutter that have SizedBox as part of their name.

  1. FractionallySizedBox – A fraction of the total available space is used to size its child.
  2. SizedOverflowBox – a specified size widget whose limitations are passed on to its child.

Make a Full-Width Button with SizedBox

Let’s construct a raised button with the same width as the screen.

Column(
        children: [
          SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                  onPressed: () {}, child: const Text('My Button')))
        ],
      ),

Output:

full width button sizedbox

Conclusion

You’ve learned the basics of how to utilize Flutter SizedBox.

Now, I’d like to hear from you: Do you know how to use the flutter SizedBox attribute? Did you think it would be this easy? 

Either way, let me know by leaving a quick comment below

In this Flutter Tutorial, we learned about the SizedBox and how to use it with examples from various circumstances.

Android TextView Alignment Justify Without Programmatically in 2023 [Java]

0

Android TextView Alignment Justify is a nice feature to align the text. Alignment defines the appearance and alignment of the margins of a paragraph: left-aligned text (justified), centered text (centered), or justified text, which aligns evenly along the left and right margins.

For example, in a paragraph that’s left-aligned (the most common alignment), the left edge of the paragraph is flush with the left margin.

In addition to the alignment property, you can also specify whether a paragraph should be indented from the left or right margin.

In this article, we will show you how to Justify Text in TextView on Android / Android TextView Alignment Justify? and the difference between justifying and non-justify.

For Android TextView Alignment Justify: You can simply use this for Justify.

Full Code of Android TextView Alignment Justify

Step 1 – Create a new project, and then follow these steps to build your first app. go to File -> New Project and fill in all required details to create a new project. We put the name of this project is Android TextView Alignment Justify.

Step 2 – Add the following codes to this activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:orientation="vertical"
   tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textSize="18sp"
        android:justificationMode="inter_word"
        android:text="Welcome to Voltage Lab. This is the Justify Text in TextView on Android. This is the feature that is introduced in Android Version greater than 8.0. Voltage Lab is the online Education Platform for Android Developers and Engineering students. Voltage also Provide the service based on the App development using native and flutter.
" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_marginTop="50dp"
        android:text="Welcome to Voltage Lab. This is not the Justify Text in TextView Android Tutorial. So you can compare both of them. The Text format is different. " />
</LinearLayout>

Step 3  − Add the following code to src/MainActivity.java

package com.example.androidtextViewalignmentjustify;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Step 4  − Add the following code to Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.androidtextViewalignmentjustify">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AndroidVerticalAlignTextview"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.Light"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Let’s try to run the application. I’m assuming you’ve connected your actual Android device with your computer.

To start the app from the android studio, open an activity file, click the run icon at the top of the toolbar, and

Select your mobile device as an option, and then check your mobile device which will display your default screen.

Android TextView Alignment Justify

This is all about the Android TextView Alignment Justify.

Read More:

Align Text to the Right Android & Vertical TextView Without Programmatically

Image Switcher in Android Example Programmatically

Align Text to the Right Android & Vertical TextView Without Programmatically in 2023 [Java]

0
Align Text to the Right

Align text to the right Android, and Android vertical align TextView is very easy to do. We can do it programmatically or by the hard code. In this article, I will show you Align text to the right android from the XML. It doesn’t matter if you use Kotlin or Java. You can do it for both platforms.

For Center Vertical in RelativeLayout: You can simply use this for vertically centered.

android:gravity="center_vertical"

For center horizontal in RelativeLayout: You can simply use this for horizontally center.

android:gravity="center_horizontal"

Full Code of Align Text to the Right Android & Vertical Align TextView

Step 1: Open Android Studio. Click on File > New Project. Enter the details about the new project.

Step2: Add the following code to res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:textColor="#FFFFFF"
        android:text="Text in Center Vertical" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:text="Welcome to Voltage Lab - Text in Center Horizontal"
        android:textColor="#FFFFFF" />
</RelativeLayout>

Step 3: Add the following code to src/MainActivity.java

package com.example.androidverticalaligntextview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Step 4  − Add the following code to Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.androidverticalaligntextview">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AndroidVerticalAlignTextview"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.Light"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

We will try to run the application. I am assuming that you have connected your actual Android mobile device with your computer.

To run the Android Studio app, click the Run icon.

Select your mobile device as an option and then check your mobile device which will display your default screen −

align text to the right android

If you have any questions regarding align text to the right android then please let us know in the comments. We love to help you.

Read More:

Image Switcher in Android Example

Image Switcher in Android Example Programmatically in 2023 [Java]

0
Image Switcher in Android Example

You don’t always want an image to appear abruptly on the screen. Sometimes you want to apply some sort of animation like an image switcher in Android example when it transitions from one image to another.

Android does have a built-in ImageSwitcher class that allows for the switching of images.

An image switcher lets you add transitions to your images when you view them on your screen.

To use Image Switcher you need to define the component’s XML first.

Syntax Image Switcher in Android Example:

<ImageSwitcher
            android:layout_width="350dp"
            android:layout_height="300dp"
            android:id="@+id/imgswitcher"
            android:layout_gravity="center"
             />

Now we will create the instance in Java file for Image Switcher in Android Example:

ImageSwitcher imageSwitcher;
imageSwitcher = (ImageSwitcher) findViewById(R.id.imgswitcher);

Now we will implement the viewfactory interface in onCreate:

 imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView view = new ImageView(getApplicationContext());
                view.setScaleType(ImageView.ScaleType.FIT_CENTER);
                view.setLayoutParams(new
                        ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
                return view;
            }
        });

The last thing you need to do is add Animation to the ImageSwitcher.

Animation classes need to be defined in this way using a static method called loadAnimation.

It’s given below:

Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
        Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);
        imageSwitcher.setInAnimation(in);
        imageSwitcher.setOutAnimation(out);

setInAnimation sets the animation of the appearance of the object on the screen whereas setOutAnimation does the opposite.

The method loadAnimation() is used to create an animation object.

Image Switcher in Android Example of Full Code:

Following is the content of the modified main activity file src/MainActivity.java for Image Switcher in Android Example.

package com.example.imageswitcher;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.app.ActionBar.LayoutParams;

public class MainActivity extends AppCompatActivity {

    ImageSwitcher imageSwitcher;
    Button buttonleft, buttonright;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonleft = (Button) findViewById(R.id.button);
        buttonright = (Button) findViewById(R.id.button2);

        imageSwitcher = (ImageSwitcher) findViewById(R.id.imgswitcher);
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView view = new ImageView(getApplicationContext());
                view.setScaleType(ImageView.ScaleType.FIT_CENTER);
                view.setLayoutParams(new
                        ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
                return view;
            }
        });

        Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
        Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
        imageSwitcher.setInAnimation(in);
        imageSwitcher.setOutAnimation(out);

        buttonleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "previous Image",
                        Toast.LENGTH_LONG).show();
                imageSwitcher.setImageResource(R.drawable.first);
            }
        });

        buttonright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Next Image",
                        Toast.LENGTH_LONG).show();
                imageSwitcher.setImageResource(R.drawable.second);
            }
        });
    }
}

Following the modified content of the xml res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="35dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Voltage Lab"
        android:textColor="#009688"
        android:textSize="35dp"
        android:textStyle="bold" />

    <ImageSwitcher
        android:id="@+id/imgswitcher"
        android:layout_width="350dp"
        android:layout_height="300dp"
        android:layout_gravity="center" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView"
            android:layout_marginRight="50dp"
            android:text="Left" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/button"
            android:layout_alignLeft="@+id/button"
            android:layout_alignParentBottom="true"
            android:text="Right" />

    </LinearLayout>
</LinearLayout>

Result of Image Switcher in Android Example

Let’s try to run the application we just modified. And see the Image Switcher in Android Example.

You can set up your AVD using the default parameters.

To run the app from Android studio, open one of your project’s activity files and click the Run icon from the toolbar.

Install android studio and run the emulator it should run and you can see the emulator window like this one.

If you have any questions regarding Image Switcher in Android Example, please let us know in comment section. To learn more about image switcher in android, you can read this article: Android imageswitcher

Read More:

Align Text to the Right Android & Vertical Align TextView Without Programmatically

What Are Keys In Flutter And When To Use It in 2023?

0
What-Are-Keys-In-Flutter-And-When-To-Use-It

In this article, we will learn about what are keys in flutter and when to use it.

We will delve into Keys in this article in Flutter. We’ll explain how to use a reasonable key in your flutter applications at a reasonable time and place in the sentences following (when, where, which).

What are the keys in Flutter?

Since widgets move around the widget tree, keys are responsible for maintaining state. When changing a collection, it’s used to keep track of the user’s scroll position or to maintain state. If the entire widget subtree is stateless, keys are not necessary. Now let us study when to use the keys.

As is common knowledge, keys are used to keep states intact when widgets are moved around the widget subtree. Therefore, a stateful widget would require keys, whereas a stateless widget would not.

To demonstrate the keys, we will build a simple application in which pressing a button will cause the color of the boxes to change. Using the keys would allow for the storage of the color values. The application developed without the use of keys is represented by the code below.

What are keys in Flutter! How useful are they?

In all but one widget constructor, the key parameters are present; however, their usage is less frequent. When widgets move around in your widget tree, keys keep their state. In actuality, this suggests that they may be helpful in maintaining the user’s scroll position or maintaining state when modifying a collection.

Making Sense of what are keys in Flutter!

Although adding keys to every Flutter widget is possible, doing so isn’t always beneficial. What you need to know about keys is this:

  • Given that these widgets hold some state, multiple widgets of the same type and level in a widget tree might not update as expected unless they have distinct keys.
  • Setting a key explicitly for a widget aids Flutter in determining which widget to update when a state change occurs.
  • Keys can store and restore a list of widgets’ current scroll positions, in addition to other things.
  • For better comprehension, think about the following example:
  • A corresponding element tree is created when Flutter arranges the widget tree. Each widget in the widget tree is internally mapped to an element in the element tree. 

People who read this article also read: Flutter LayoutBuilder Widget Example Step by Step

Each element in the element tree contains information about the UI and the app’s structure, so each element contains specifics about:

  1. The widget’s runtimeType for that widget in the widget tree.
  2. A pointer to the corresponding widget in the widget tree.
  3. The reference is to its child element.

When to use it?

When changing a group of widgets of the same type that are holding a state, keys are frequently used. The majority of the time, we use them on children of widgets, like Listview or Stateful widgets, whose data is constantly changing.

Why to use it?

What are keys in flutter? and how to use it? The key idea is how flutters maintains a reference to state and allows access to it at various times, or keeps it while modifying the widget tree.

Before re-rendering, Flutter checks the previous state, and if the previous widget is the same type as the new one, it will keep the previous state.

If the data is changing, we don’t want this because flutter will continue to use the outdated information. To uniquely identify the widget, we therefore need keys. This is due to the fact that a new widget will have a unique key, destroying the old one.

Key types in Flutter

  1. Value Key: The value key is used when something constant and extraordinary must be assigned to it. For example, in the To-Do List, the text entered is the value.
  2. Object Key: The Object key is used when a single field, like a person’s name or birthday, may be the same for more than two people but is different for every individual or every set of data.
  3. Unique Key: When there are multiple widgets with the same incentive, we must define each widget as a separate item using the unique key. Since we didn’t know what random color would be assigned to it until the widgets were put together, we also used it in our code.
  4. Global Key: The benefit of using a global key is that it holds data that other widgets in the code can access. Use the Global KeyFrom State>, which stores a form of state and prevents other widgets from accessing the data it contains, if you don’t want to share it with other widgets.

Global keys have two uses.

  • In addition, they can be used to access information about another widget in a completely different branch of the widget tree, allowing widgets to change their parents anywhere in the application without losing state.
  • In the second scenario, you might need to check the password, but you would prefer not to share the status information with various widgets in the tree, so you can use the GlobalKeyFromState>Hold a formFormOfState.

In actuality, global keys are similar to global variables. The function of global keys can be performed more effectively by inherited widgets, Redux, or block patterns, for example.

How to Use Keys to Prevent Unexpected Results

Flutter can perform an additional comparison in addition to the widget type by adding a key to a widget that stores a reference to the state. By doing this, Flutter makes sure that when the types and keys match, but the keys don’t, the elements are forced to drop to their widget reference. They hold references to widgets that match both the type and key. This ensures that both the widget and state references are properly updated.

The Starter Project’s setup

  1. Open an existing project by selecting it in Android Studio. 
  2. Then pick the starter folder from the materials you downloaded.
  3. When you are in this file, click Pub get at the top of the pane to fetch the dependencies listed in pubspec.yaml.

Now that you know what the starter project contains, you’ll take a deeper look at what are keys in flutter and when to use it.

People who read this article also read: How to Use the Flutter Positioned Widget?

Stateless Widget Tree

  • We have created the application using the stateless widget in this section of the code. 
  • PositionedTiles is a new class that is created here. 
  • The comment you see in this code is for the special color generator, which will generate the colors for the boxes at random. 
  • The swapTiles function is activated when the button is tapped, and the swapping then occurs. The smiling face at the bottom is the onTap button.
import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(new 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: Text("GEEKSFORGEEKS"),
		backgroundColor: Colors.green,
	) ,
	body: SafeArea(child: Row(children: tiles)),
	floatingActionButton: FloatingActionButton(
		child: 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: 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 = new Random();
static Color getColor() {
	if (colorOptions.length > 0) {
	return colorOptions.removeAt(random.nextInt(colorOptions.length));
	} else {
	return Color.fromARGB(random.nextInt(256), random.nextInt(256),
		random.nextInt(256), random.nextInt(256));
	}
}
}


Output:

You can see that the colors are changing here, but if we switch to the Stateful widget, the code will still function properly but the application won’t display anything. But as long as we use the keys in this Stateful widget, the application will function properly. Direct with the keyboard is the next code, which is shown below. 

Stateful Widget Tree

As you can see in this code, we have used the keys feature, which is why the application is operating properly. Only the Key feature has been added here; the remaining code is unchanged.

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

void main() => runApp(new 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: Text("GEEKSFORGEEKS"),
		backgroundColor: Colors.green,
		) ,
	body: SafeArea(child: Row(children: tiles)),
	floatingActionButton: FloatingActionButton(
		child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles),
	);
}

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

class StatefulColorfulTile extends StatefulWidget {
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: 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 = new Random();
static Color getColor() {
	if (colorOptions.length > 0) {
	return colorOptions.removeAt(random.nextInt(colorOptions.length));
	} else {
	return Color.fromARGB(random.nextInt(256), random.nextInt(256),
		random.nextInt(256), random.nextInt(256));
	}
}
}


Output

Now that we have seen the example above, it is obvious where to add them. The solution is straightforward: if you must use the Stateful widget, then you must use the Keys; otherwise, there is no need to use them.

What am I going to do with them?

Short answer: if you need to add keys to your app, place them at the top of the widget subtree with the state you want to keep.

People frequently make the mistake of believing that they only need to put a key on the first stateful widget, but there are dragons. Still not convinced? To demonstrate how far we can go, I wrapped my colorfulTile widgets in padding widgets but left the keys on the tiles.

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

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

class PositionedTilesState extends State<PositionedTiles> {
  // Stateful tiles now wrapped in padding (a stateless widget) to increase height 
  // of widget tree and show why keys are needed at the Padding level.
  List<Widget> tiles = [
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: StatefulColorfulTile(key: UniqueKey()),
    ),
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: StatefulColorfulTile(key: UniqueKey()),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(children: tiles),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles),
    );
  }

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

class StatefulColorfulTile extends StatefulWidget {
  StatefulColorfulTile({Key key}) : super(key: key);
 
  @override
  ColorfulTileState createState() => ColorfulTileState();
}

class ColorfulTileState extends State<ColorfulTile> {
  Color myColor;

  @override
  void initState() {
    super.initState();
    myColor = UniqueColorGenerator.getColor();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: myColor,
        child: Padding(
          padding: EdgeInsets.all(70.0),
        ));
  }
}

Currently, the tiles change to completely random colors when I click the button!

Output:

what are keys in flutter

Conclusion

You’ve learned the basics of what are keys in flutter and when to use it 

Now, I’d like to hear from you: what are keys in flutter and when to use it? Did you think it would be this easy? 

This was a brief basic introduction of what are keys in flutter and when to use it. I have described the basic structure of Keys in Flutter in the article; you are free to modify this code as you see fit.

I’m hoping that the information on this blog will be sufficient for you to use in your flutter projects to try out keys. Use theKey when maintaining the widget tree’s state is required. When modifying a list of widgets, for instance, or a collection of the same kind. WillKeySet is placed at the top of the widget tree to show exceptional identity (which picks different kinds of keys). So please try it.

Read More:

How to use the Rive Flutter Animation

Sources: Image and code from geeksforgeeks and flutteragency.

How to Use the Flutter Positioned Widget? (2023)

0
How to Use the Flutter Positioned Widget

This article will walk you through the process of using Flutter positioned.

In order to create the children of a Stack widget, you need to control each of its places. Now to do so you can wrap some of the children using the Positioned widget. A child of a Stack widget can be positioned using the widget named Positioned. Flutter Positioned Widget is a widget that comes built-in with the Flutter SDK. It’s a way of placing arbitrary widgets on top of each other.

Things you’ll learn after reading this article:

  1. How this method helps to position child widgets inside a Stack widget, or similar.
  2. As the children of a Stack widget are created, how, you can control where each child should be placed?

Below are examples of how to use the widget. In this tutorial, I will discuss the Flutter Positioned widget.

Flutter Positioned

Now on to the fun stuff!

I suppose you know the basics of Flutter by now. So we are going to learn about the steps and types of ways to use the Flutter positioned widgets.

This article will also provide the codes as well as the output to make it easier for you. So, let’s get started.

Utilizing Flutter Positioned

Types of Flutter Positioned Commands:

  1. Positioned
  2. Directional
  3. Fill
  4. FromRect
  5. FromRelativeRect

A positioned widget must stay inside the Stack widget.

StatelessWidget and StatefulWidget cannot be children of Positioned widgets.

We can’t allow other kinds of widgets such as RenderObjectWidget.

Positioned widget contains a few properties that affect the size and position of child widgets.

  • There are five properties that you can use to adjust the size and position of your widget: left, top, right, bottom, and width. Height is not among them.
  • The first four properties are in use to set the position of the child relative to the edge. For example, the use of the left property is to set the position relative to the left edge.
  • The last two properties, width, and height, are in use to set the child widget’s width and height respectively.
  • You can create a Positioned widget by using any of its constructors.

Positioned Constructor

It generates a widget that controls the location of a Stack’s child.

The use of the default constructor is to specify values for the properties indicated above. It allows to assign the characteristics horizontal values (left, right, and width) as well as vertical values (top, bottom, and height). You can only alter two of the three horizontal values. Because specifying all three horizontal values prohibits Flutter from calculating position and size, it makes sense. The same may be said for vertical values. If you violate that rule, you will receive an assertion error.

The Positioned class has some constructors, such as named and factory constructors.

The argument constructors allow you to set the properties above.

const Positioned(
{Key key,
double left,
double top,
double right,
double bottom,
double width,
double height,
@required Widget child}
)

So we have to put the value of this constructor.

      body: Container(
        width: 400,
        height: 400,
        decoration: BoxDecoration(border: Border.all()),
        child: Stack(
          children: [
            //Flutter Positioned widgets here
            Positioned(
              top: 40,
              bottom: 40,
              left: 70,
              right: 10,
              child: Container(
                width: 1,
                height: 1,
                color: Colors.blue,
              ),
            )
          ],
        ),
      ),


Output:

Flutter Positioned Widget

Positioned.Directional Constructor

Using the constructor is fairly similar to using positioned.directional. The rule that states that you can only set two out of three horizontal and vertical values also applies to this factory constructor. 

  • Only two of the three horizontal values (start, end, and width) and two of the three vertical values (top, bottom, and height) can be specified. 
  • Positioned.directional defines the horizontal location of the widget using start and finish but has an explicit TextDirection.  At least one of the three must be null in each circumstance.

The left and right parameters have been replaced by start and finish arguments. When the value is set to ltr, the value supplied as the start argument is used for the left property, while the value passed as the end argument is used for the right property.  When the value is set to rtl, the value supplied as the start argument is used for the right property, while the value passed as the end argument is used for the left property. As a result, you must give a TextDirection value as the textDirection parameter to designate which one is the start edge (left or right).

 factory Positioned.directional({
    Key? key,
    required TextDirection textDirection,
    double? start,
    double? top,
    double? end,
    double? bottom,
    double? width,
    double? height,
    required Widget child,
  })

So we will put the value:

      body: Container(
        width: 400,
        height: 400,
        decoration: BoxDecoration(border: Border.all()),
        child: Stack(
          children: [
            // Positioned widgets here
            Positioned.directional(
              textDirection: TextDirection.rtl,
              end: 20,
              top: 20,
              start: 50,
              bottom: 15,
              child: Container(width: 50, height: 100, color: Colors.green),
            ),          ],
        ),
      ),


Output:

Positioned.directional

Positioned.Fill Constructor

This designated parameter may be used to construct a Positioned object and set the values for the attributes left, top, right, and bottom. Moreover, if none of the attributes are given, the default value is 0.0.

const Positioned.fill({
    Key? key,
    double? left = 0.0,
    double? top = 0.0,
    double? right = 0.0,
    double? bottom = 0.0,
    required Widget child,
  }

So we will put the value:

   // Positioned widgets here
          Positioned.fill(
          left: 20,
          top: 20,
          right: 20,
          bottom: 20,
          child: Container(width: 50, height: 100, color: Colors.red),
        ),

Output:

position fill

Positioned.FromRect Constructor

This constructor is used to produce a Positioned object from a Rect. The Rect returns the values left, top, right, and bottom, but the height and width properties are set to null.

 Positioned.fromRect({
    Key? key,
    required Rect rect,
    required Widget child,
  })

Put the code:

            Positioned.fromRect(
              rect: Rect.fromCenter(center: Offset(100, 100), width: 150, height: 150),
              child: Container(width: 50, height: 100, color: Colors.amber),
            ),


Output:

flutter position rect

Positioned.FromRect Constructor

This constructor is used to produce a Positioned object from a Rect. So, the Rect returns the values left, top, right, and bottom, but the height and width properties are set to null.

Conclusion

I hope you enjoyed my ultimate guide to your question: how to use a flutter positioned widget?

So, to answer your question about the flutter positioned attribute, look at the above commands for the best results.

Now, I’d like to hear from you: Do you know how to use the flutter positioned attribute? Did you think it would be this easy? 

Either way, let me know by leaving a quick comment below.

Read More:

Flutter LayoutBuilder Widget Example Step by Step

Rive Flutter Animation | Best Approach For Animation in 2023

0
Rive-Flutter-Animation--Best-Approach-For-Animation

In this article, I will show you how to construct the code component in Rive Flutter Animation. Though the logic is pretty similar to React Native.

Rive Flutter is an interactive design and animation tool that works in real-time. 

Introduction to Rive Flutter Animation  

You can quickly import your Rive assets to FlutterFlow and use them within your app by using the RiveAnimation widget.

  1. Rive is a fantastic animation tool that allows us to create beautiful animations that we can then incorporate into our application. 
  2. We can add animations in Flutter by writing a lot of code, but this is not a good practice for a developer. 
  3. This robust Rive animation tool allows us to create animation without having to write lines of code. 

Let’s imagine you develop a screen responsible for downloading a significant amount of data. But there’s a problem: how can you keep the users entertained while the files are being sent?

If presenting animations was the first thing that came to mind, you’re not alone! And if you have any questions or are unsure how to get started with Flutter animations, this article should help.

To fully comprehend the topic, please read all the points below in order.

Why should mobile apps have animations?

A clean, appealing interface alone is no longer sufficient to pique users’ interest.

What can you do to persuade people to try your solution?

  1. Ensure that users have a sense of control. 
  2. They must be aware that their actions have consequences. 
  3. The app should provide feedback to users every time they do something. 
  4. This way, they can quickly learn how to use your product and are more likely to open the app in the future.

What other advantages can animations provide? 

  • They use information about the sale, for instance, to direct the user’s attention to a particular location. 
  • They also ensure that the sequential screens transition smoothly. 
  • As a result, there is a higher likelihood of creating a satisfying user experience. 
  • Particularly if the animations relate to the products you sell and have a design that matches your branding elements.

Beginning with Flutter

  1. The command Prompt can be used to create a new Flutter application. For creating a new app, write flutter create YOUR_APP_NAME and run this command.
  2. Launch the application in Android Studio or VS Code. I am using VS Code.
  3. For the time being, remove the default code from main.dart.
  4. Now it’s time to make a new animation. Go ahead to https://rive.app/explore/popular/trending/all.
  5. Additionally, you can export animations that other users have made. 
  6. “Open in Rive” will appear when you click any animation. 
  7. Then download it by clicking the export button.
  8. The file extension and format should be.flr and Binary, respectively.
  9. Now, open VS Code and create a new folder “assets” in the application’s root directory and paste the files you downloaded from rive. In the asset’s folder, I have four files.
Rive Flutter Command Prompt
Rive Flutter Command Prompt

Animation Design

Using Rive Flutter Editor, you can start from scratch to create an animation.

  1. Select + New File.
  2. Set the width and height of the artboard.
  3. Then, select Create.

To begin creating your animation, use the Rive Flutter design tools or import image files. Once your design is complete, you can use the timeline.

People also read: How to Use the Flutter Positioned Widget?

Inserting the RiveAnimation widget for Rive Flutter

To use a Rive animation, follow these instructions:

  1. Onto the canvas, drag and drop the RiveAnimation widget.
  2. Choose Network or Asset as the Animation Source.
  3. Enter the path (download URL) of the animation if the network is in selection. 
  4. Get the route by choosing the Rive Flutter animation that is in the community, then selecting the Download button and selecting Copy Link Address from the menu that appears.
  5. Considering you chose Asset, 
  6. From the drop-down menu, select an artboard.
  7. Choose the animations you want to use (these were imported from the Rive Flutter asset). You can play one or more animations after selecting them with the Preview Animations button.
  8. By default, the animation type is set to once. You will have the option to choose Continuous if the animations you’ve chosen have loops or boomerangs. If the animation has a loop, selecting this option will make it play continuously.
  9. The Auto Animate checkbox is left checked by default, which means that the animation will begin as soon as the page loads. Uncheck this if you want to use an action to initiate the animation.
  10. Set the RiveAnimation widget’s width and height, and then select a Box Fit type.

(Optional) If you intend to use an Action to trigger the animation, you can give this RiveAnimation widget an appropriate Name so that it is easily identifiable.

How does Flutter aid in the production of animations?

To create effective animations that are also aesthetically pleasing, Flutter is the ideal tool. Your imagination is the only limit. In order to create a cross-platform app, let’s now talk about how to add an animation.

Types of Flutter Animation

Explicit and implicit animations are the two main categories of animations (or rather, their types). 

What distinguishes them from one another?

Implicit Animation

You can select an implicit animation if it depends only on a widget’s available variables (like size or color). As a result, you employ Flutter’s pre-installed widgets, such as AnimatedContainer, AnimatedOpacity, AnimatedCrossFade, and numerous others.

When the given value changes, the animation is created.

Explicit Animation

Explicit animations require you to set their behavior on your own, so you must do so. These animations make use of AnimationController. Their advantage is that they provide more options than the implicit type while maintaining all of its functionalities.

Animation Techniques

I should mention that the platform supports three types of animation:

  • One-shot – one-time display of the animation
  • Ping-pong – an infinite display of animation in a sequence from beginning to end.
  • Loop – displays the animation indefinitely from the beginning.

From the code level, Rive Flutter gives you the option to modify the animation’s presentation. The state machine in Rive Flutter allows you to influence which animations the state machine plays by allowing you to make changes to the animations you create.

The animation that should be shown during the day is changed when the button is tapped, for instance, from the one that appears at night. In the animation’s state machine, it switches from day to night at the same time.

Animating a jumping square

You can now start coding.

  1. Create a StatefulWidget-based BouncingAnimationWidget to begin building Flutter animation. 
  2. Use the SingleTickerProviderStateMixin for this purpose. 
  3. It’s a mixin that controls how often the animations are refreshed. 
  4. It ensures Ticker, which allows Flutter’s engine to display animations at 60 frames per second. 
  5. The AnimationController—the entity in charge of overseeing everything—is then declared.
class BouncingAnimationWidget extends StatefulWidget {
 const BouncingAnimationWidget({Key? key}) : super(key: key);
 @override
 State<BouncingAnimationWidget> createState() =>
     _BouncingAnimationWidgetState();
}
class _BouncingAnimationWidgetState extends State<BouncingAnimationWidget>
   with SingleTickerProviderStateMixin {
 late final AnimationController _controller;
 @override
 void initState() {
   super.initState();
   _controller = AnimationController(
     duration: const Duration(milliseconds: 500),
     vsync: this,
   );
 }
@override
 Widget build(BuildContext context) {
   return Scaffold();
 }
 @override
 void dispose() {
   _controller.dispose();
   super.dispose();
 }
}

Now that you have a square with a shadow, you can start animating it.

Stack(
         alignment: Alignment.center,
         children: [
           _boxShadow(context),
           Align(
             alignment: Alignment(0.0, _boxJumpHeight.value),
             child: _animatedBox(context),
           ),
         ],
       ),

Widget _boxShadow(BuildContext context) => Container(
       width: 180,
       height: 15,
       decoration: BoxDecoration(
         borderRadius:
             BorderRadius.all(Radius.elliptical(180, 15)),
         boxShadow: [
           BoxShadow(
             color: Colors.black.withOpacity(0.15),
             spreadRadius: 5,
             blurRadius: 4,
             offset: const Offset(0, 3),
           ),
         ],
       ),
     );

 Widget _animatedBox(BuildContext context) => Container(
         width: 160,
         height: 50,
         color: Colors.white,
       );

Next, add the animations by spacing them out at specific intervals.

void _initJumpAnimation() => _boxJumpHeight = Tween<double>(
       begin: -0.07,
       end: -0.5,
     ).animate(
       CurvedAnimation(
         parent: _controller,
         curve: const Interval(
           0.0,
           1.0,
           curve: Curves.easeInOut,
         ),
       ),
     );
 
 void _initBoxRotationAnimation() => _boxRotationAngle = Tween<double>(
       begin: 0,
       end: 360,
     ).animate(
       CurvedAnimation(
         parent: _controller,
         curve: const Interval(
           0.25,
           1.0,
           curve: Curves.ease,
         ),
       ),
     );
 
 void _initBoxWidthAnimation() => _boxWidth = Tween<double>(
       begin: 160,
       end: 50,
     ).animate(
       CurvedAnimation(
         parent: _controller,
         curve: const Interval(
           0.05,
           0.3,
           curve: Curves.ease,
         ),
       ),
     );
 
 void _initBoxShadowWidthAnimation() => _boxShadowWidth = Tween<double>(
       begin: 180,
       end: 50,
     ).animate(
       CurvedAnimation(
         parent: _controller,
         curve: const Interval(
           0.05,
           0.5,
           curve: Curves.ease,
         ),
       ),
     );
 
 void _initBoxShadowIntensityAnimation() =>
     _boxShadowIntensity = Tween<double>(
       begin: 0.15,
       end: 0.05,
     ).animate(
       CurvedAnimation(
         parent: _controller,
         curve: const Interval(
           0.05,
           1.0,
           curve: Curves.ease,
         ),
       ),
     );

When the animations are already there, give users the option to run them concurrently with the rectangle’s rotation. The static values ought to switch to those governed by the specific animations.

The widget now ought to appear as follows:

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

@override
 State<BouncingAnimationWidget> createState() =>
     _BouncingAnimationWidgetState();
}
 
class _BouncingAnimationWidgetState extends State<BouncingAnimationWidget>
   with SingleTickerProviderStateMixin {
 late final AnimationController _controller;
 late final Animation<double> _boxJumpHeight;
 late final Animation<double> _boxWidth;
 late final Animation<double> _boxShadowWidth;
 late final Animation<double> _boxShadowIntensity;
 late final Animation<double> _boxRotationAngle;
 
 @override
 void initState() {
   super.initState();
   _controller = AnimationController(
     duration: const Duration(milliseconds: 500),
     vsync: this,
   );
   _initJumpAnimation();
   _initBoxWidthAnimation();
   _initBoxShadowWidthAnimation();
   _initBoxShadowIntensityAnimation();
   _initBoxRotationAnimation();
 }
 // Insert init functions from the last paragraph here
 @override
 Widget build(BuildContext context) => AnimatedBuilder(
       builder: (context, _) => _buildAnimation(context),
       animation: _controller,
     );
 
 Widget _buildAnimation(BuildContext context) => GestureDetector(
       onTap: _playAnimation,
       child: Stack(
         alignment: Alignment.center,
         children: [
           _boxShadow(context),
           Align(
             alignment: Alignment(0.0, _boxJumpHeight.value),
             child: _animatedBox(context),
           ),
         ],
       ),
     );
 
 Future<void> _playAnimation() async {
   try {
     await _controller.forward().orCancel;
     await _controller.reverse().orCancel;
   } on TickerCanceled {
     // the animation got canceled
   }
 }
 
 Widget _boxShadow(BuildContext context) => Container(
       width: _boxShadowWidth.value,
       height: 15,
       decoration: BoxDecoration(
         borderRadius:
             BorderRadius.all(Radius.elliptical(_boxShadowWidth.value, 15)),
         boxShadow: [
           BoxShadow(
             color: Colors.black.withOpacity(_boxShadowIntensity.value),
             spreadRadius: 5,
             blurRadius: 4,
             offset: const Offset(0, 3),
           ),
         ],
       ),
     );
 
 Widget _animatedBox(BuildContext context) => Transform(
       alignment: Alignment.center,
       transform: _boxRotation(_controller.status),
       child: Container(
         width: _boxWidth.value,
         height: 50,
         color: Colors.white,
       ),
     );
 
 Matrix4 _boxRotation(AnimationStatus animationStatus) {
   // This will ensure that rotation will be in the same direction on reverse
   if (animationStatus == AnimationStatus.reverse) {
     return Matrix4.identity()..rotateZ(-_boxRotationAngle.value * pi / 180);
   } else {
     return Matrix4.identity()..rotateZ(_boxRotationAngle.value * pi / 180);
   }
 }
 
 @override
 void dispose() {
   _controller.dispose();
   super.dispose();
 }
}

Output

Making use of animations in the app

You must use the Rive Flutter developers’ package once the animations have been created. Launch a new project, add an asset to it, then build a widget that will download the animation (from the file or the web).

class FlutterServiceWidget extends StatefulWidget {
 const HoldappLogoRiveWidget({Key? key}) : super(key: key);
 
 @override
 State<HoldappLogoRiveWidget> createState() => _HoldappLogoRiveWidgetState();
}
 
class _FlutterServiceWidgetState extends State<HoldappLogoRiveWidget>
   with SingleTickerProviderStateMixin {
 Artboard? _riveArtboard;
 
 @override
 void initState() {
   super.initState();
   rootBundle.load('assets/holdapp_logo.riv').then((data) {
     // Load the RiveFile from the binary data.
     final file = RiveFile.import(data);
 
     // The artboard is the root of the animation
     // and gets drawn in the Rive widget.
     final artboard = file.mainArtboard;
     var controller =
         StateMachineController.fromArtboard(artboard, 'State Machine 1');
     if (controller != null) {
       artboard.addController(controller);
     }
     setState(() => _riveArtboard = artboard);
   });
 }
 
 @override
 Widget build(BuildContext context) => Scaffold(
       backgroundColor: Colors.white,
       body: _riveArtboard != null
           ? Rive(artboard: _riveArtboard!)
           : const Center(
               child: CircularProgressIndicator(),
             ),
     );
}

Output:

Conclusion

You’ve learned the basics of how to utilize Rive Flutter Animation 

Now, I’d like to hear from you: Do you know how to use Rive flutter? Did you think it would be this easy? 

Rive Flutter enables developers to produce stunning, interactive animations and deliver them to any platform. Because of their open-source runtimes, creators can create animations once and then publish them on any platform they choose.

This, however, wasn’t always the case. The team initially spent a significant amount of time managing the development cycle, including maintaining various client-side web packages for a large portion of the UI functionality, a custom build process, custom dev ops, custom testing, linting, language servers, and more — all from separate packages that required maintenance and constant updating.

Either way, let me know by leaving a quick comment below.

In this Flutter Tutorial, we learned about Rive and how to use it with examples from various circumstances.

Sources: holdapp websites.

Read More:

Flutter LayoutBuilder Widget Example Step by Step

Flutter LayoutBuilder Widget Example Step by Step in 2023

0
Flutter Layoutbuilder Widget Example

This article will enable you to understand flutter layoutbuilder easily with examples. The Google-developed Flutter is not hard to master to begin with.

Flutter makes it very simple for developers to create a dynamic user interface. Flutter is a free and open-source tool for building mobile, desktop, and online apps with code. Pulsation automated testing enables you to achieve high responsiveness in your application by assisting in the discovery of bugs and other difficulties. Let’s see what we are going to discuss from flutter layoutbuilder.

An Overview of Flutter Layoutbuilder

Flutter, Google’s UI toolkit, allows you to quickly create stunning, responsive, natively integrated apps for mobile, web, and desktop using a single codebase performance. Flutter offers outstanding developer tools, with exceptional hot reload.

Flutter LayoutBuilder widget assists you in creating a widget tree that is dependent on the size of the parent widget (a minimum and maximum width, and a minimum and maximum height).

  • The LayoutBuilder Widget in Flutter is similar to the Builder widget. 
  • Flutter LayoutBuilder widget framework uses the builder function during layout. 
  • It supplies the parent widget’s restrictions. 
  • This is helpful when the parent limits the child’s size and does not rely on the child’s inherent size. 
  • The ultimate size of the LayoutBuilder will be the same as the size of its child.

The builder function is used in the following circumstances:

  • The first time, the widget is arranged.
  • When the parent widget satisfies various layout criteria.
  • When the parent widget is updated, this widget gets updated.
  • The dependencies to which the constructor function subscribes alter.

People who read this article also read: How to Use the Flutter Positioned Widget?

Layout Builder

LayoutBuilder aids in the creation of a widget tree in the widget flutter. The size of it is dependent on the size of the original widget. The layout builder may be sent to flutter as a parameter. 

It has 2 functions

  1. Build context
  2. Boxconstrant

BuildContext is a widget name. However, the box constraint is more essential. Since it provides the width to the parent widget, which is used to control the child based on the size of the parent.

Difference between Flutter LayoutBuilder and MediaQuery

Adapting a layout to a platform may enable us to reach a larger audience. Another consideration is the vast variety of various devices, which presents additional hurdles to developers.

Developing to support numerous screen sizes is a difficulty that will always be present in a developer’s life, thus we need tools to best adapt to this. Flutter, once again, provides us with the tools we need to understand the environment in which the app operates so that we can act on it.

Flutter’s key classes for this purpose are LayoutBuilder and MediaQuery.

“The key difference between Media Query and LayoutBuilder is that Media Query uses the entire screen context rather than the size of your specific widget. While every widget’s maximum width and height are set by the layout designer.”

Implementation of the Code

You can use it in your code like the following part:

  1. Inside the lib folder, create a new dart file named main.dart. Or create the new project by VS code or Android Studio.
  2. Now we’ll go through the LayoutBuilder() class.
  3. Before utilizing the LayoutBuilder class, we created a container widget that will house the LayoutBuilder. 
  4. The layout builder features three containers, each with its own color, text, and condition.
  5. If the user specifies a device width of more than 480, two container boxes will emerge, which will be visible when the tablet or screen is turned horizontally. 
  6. Otherwise, the standard container will be seen. 

Let us go through this in more depth with the assistance of a reference.

Syntax:

LayoutBuilder(
  builder: (BuildContext context, BoxConstraints constraints) {
    return Widget();
  }
)

Basic Example 1: When we use the parent’s constraints to calculate the child’s constraints, most commonly we use the flutter layoutbuilder widget.

import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Layout Builder Widget Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        color: Colors.blueGrey,
        /// using MediaQuery
        /// [container's height] = [(phone's height) / 2]
        height: MediaQuery.of(context).size.height * 0.5,
        width: MediaQuery.of(context).size.width,
        /// Aligning contents of this Container
        /// to center
        alignment: Alignment.center,
        child: LayoutBuilder(
          builder: (BuildContext ctx, BoxConstraints constraints) {
            return Container(
              color: Colors.blueAccent,
              /// Aligning contents of this Container in center
              alignment: Alignment.center,
              /// just now calculate child's height and width
              height: constraints.maxHeight * 0.7,
              width: constraints.maxWidth * 0.7,
              child: const Text(
                'Flutter LayoutBuilder Widget',
                style: TextStyle(
                  fontSize: 22,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

Output:

flutter layout builder basic widget

Example 2: Now we will see the multiple display different UI’s for different screen sizes for flutter layoutbuilder.

import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Layout Builder Widget Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        height: MediaQuery.of(context).size.height * 0.5,
        width: MediaQuery.of(context).size.width,

        alignment: Alignment.center,

        child: LayoutBuilder(
          builder: (BuildContext ctx, BoxConstraints constraints) {
            if (constraints.maxWidth >= 480) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    alignment: Alignment.center,
                    height: constraints.maxHeight * 0.5,
                    color: Colors.blueGrey,
                    child:const Text(
                      'Left Part of Screen',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    alignment: Alignment.center,
                    height: constraints.maxHeight * 0.5,
                    color: Colors.blueAccent,
                    child: const Text(
                      'Right Part of Full Screen',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              );
              // If screen size is < 480
            } else {
              return Container(
                alignment: Alignment.center,
                height: constraints.maxHeight * 0.5,
                color: Colors.redAccent,
                child:const Text(
                  'Flutter Normal Screen',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              );
            }
          },
        ),
      ),
    );
  }
}

flutter layoutbuilder widget Output:

flutter-layoutbuilder-full

Conclusion

You’ve learned the basics of the LayoutBuilder widget and seen some examples of how to use it.

Now, I’d like to hear from you: Do you know how to use the flutter positioned attribute? Did you think it would be this easy? 

Either way, let me know by leaving a quick comment below.

To know more about layoutbuilder, you can read article from flutter doc.