Author

admin

Browsing

What Is The Advantages Of Machine Learning?

ENIAC, the first computer, could perform 5,000 additions per second. In comparison, an average person can perform approximately 0.4 additions per second.

This means the first computer was about 12,500 times faster than a human.

Now, in today’s world, computers can perform billions of operations per second. When machines, particularly computers, learn to imitate human behavior—through machine learning—the potential is extraordinary.

They can outperform us in a matter of seconds.

So, let’s talk about the advantages of Machine Learning.

Automated decision without human intervention

One of the noted advantage is that, it does not need a human intervention for making decisions. It will think like human or based how the model is set it up, and make decisions.

It will do as same like human do and sometimes better, especially in repetitive, data-driven, or time-sensitive scenarios.

Personalization

Every client or user is treated as a top priority, No differentiation occurs—each user receives the same level of attention and care. Based on individual patterns, preferences, likes, and dislikes, machine learning models understand what to suggest and what to avoid.

For example, platforms like YouTube, Netflix, and Amazon use machine learning to power their recommendation systems. These systems treat each user uniquely, tailoring content or product suggestions to match personal behavior and interests.

24*7 availability

They are available whenever anyone needs them. No need for rest, sleep, or food like humans do. It means, whenever people need any help from deployed machine learning, it will be done.

Improvement Over Time

Just like experienced professionals improve with time, machine learning models also get better as they are exposed to more data. As the model continues to receive new data after deployment—even data it wasn’t originally trained or tested on—it can adapt, refine its predictions, and improve overall performance.

Using techniques like continuous learning or model retraining, the system becomes more accurate and efficient in handling real-world scenarios.

Handles Large Sets of Data

In this information age, there is a vast amount of data in various formats—text, audio, video, and more. It is very difficult for humans to handle all this data accurately because the chances of mistakes are high. However, machines operate using only 0s and 1s (binary), so they convert every type of data into this format to process and understand it efficiently. While humans converting data into binary might become complex as data volume grows, machines are built to handle and process large datasets quickly and accurately.

Less cost when compared to human

In the long term, its cost is considered to be less compared to humans, and machines can work 24*7. Once implemented, the ongoing costs—such as maintenance, updates, and electricity—are relatively low when spread over many years.

This makes machine learning a cost-effective solution for businesses looking to automate processes and improve efficiency.

New ML Job Opportunities

In the job zone, ML has come with new opportunities such as:

  • Data Scientist
  • ML Engineer
  • MLOps Engineer
  • Prompt Engineer

with competitive salary.

Beyond technical roles, ML is also creating opportunities in ethical AI, AI policy, and AI product management, reflecting the broader ecosystem around machine learning technologies.

Disadvantages of Machine Learning

Just like its advantages, Machine Learning also has disadvantages.

Let’s talk about that too.

Large Data Needed for Training

The model needs to be trained on a large number of high-quality datasets. If the dataset is small or of low quality, it may lead to poor or average predictions. The model also needs to be trained with new data regularly; otherwise, the ML model will degrade over time.

Resources for Training Are Expensive

For large ML models, training requires CPUs or GPUs. This is actually very expensive, both for renting and buying. They also need expensive infrastructure, as training produces heat that must be controlled to ensure better performance and to prevent overheating.

Job Loss

Due to automation of tasks and significantly better output in less time, there may be increased job losses in different sectors. Most companies have started using AI, which may result in job loss for new joiners or less experienced people. However, ML also creates new opportunities based on machine learning. Still, data typing and most basic tasks are expected to be handled by AI or machine learning in the future.

Manipulation with Malicious Data

Biased and malicious data can significantly alter decisions and lead to incorrect predictions. Manipulation can happen at any time—it may occur during fine-tuning with user feedback or from biased data collected during scraping or training in the machine learning model lifecycle.

Lack of Transparency in How Decisions Are Made (Black Box Problem)

It is often unclear how decisions are made based on the data. In some cases, it is difficult to understand why a particular outcome occurred. This lack of transparency makes debugging and improving predictions more challenging.

Reference:

Machine Learning Model Lifecycle – What I Understand

Everything undergoing creation or use will have lifecycle.

In Machine learning, There are 2 terms Machine learning lifecycle and machine learning model lifecycle.

They might seem quite similar at first glance, but actually, the Machine Learning Model Lifecycle is just a subset of the broader Machine Learning lifecycle.

In short,

  • Machine learning lifecycle: tells about the whole process. – managing entire mobile factory.
  • Machine Learning Model lifecycle: tells only about the machine learning model- managing one Mobile.

At first, I thought that Model Creation -> Model Training -> Model Deployment, these are the steps, but there’s much more to it.

Steps in the Machine learning model lifecycle:

machine learning model lifecycle
1. Model designing
2. Model training
3. Model Evaluation
4. Model deployment
5. Model monitoring
6. Model maintenance or retraining.
7. Model retirement

1. Model Designing

This is the first phase in model building. Here, we decide what type of algorithm to use, what kind of input and output the model should handle, and where the model will be deployed for user access.

In this phase, we can say that the model structure is completed.

2. Machine training

After creating the model, we need to train it. We already selected an appropriate algorithm and use it to help the machine, learn from the data by identifying patterns.

The data can come from your own sources such as your proprietary records (medical records, bank transactions) or publicly available repositories like Kaggle. This data is then fed to the model, and the model learns from it.

3. Model Evaluation

We need to test the model using unseen data to evaluate its performance. This testing data should not have been used during the training process. Evaluating with new data helps us understand how well the model generalizes to real-world scenarios.

If we skip this step, there’s a high chance the model may fail in production.

4. Model Deployment

To make the model available to users, we need to deploy it—usually by hosting it somewhere. This could be on a server, cloud, or even on edge devices like IoT hardware or mobile phones.

However, large models often can’t be deployed on low-resource devices due to hardware limitations. We can expose the model through an API, allowing users or other systems to access it over the internet.

5. Model monitoring

Still, we need to monitor the model because the model cannot be 100% right in every prediction. Still, many models in production are making mistakes.

ChatGpt, Gemini also says they can make mistakes, right? That’s why this phase is very important. As new data comes in, the model may make wrong decisions.

6. Model retraining

New data or queries can come in during monitoring, after deployment, or from other sources. When this happens, we need to retrain the model to improve its prediction accuracy.

This phase is important for continuously improving the model’s performance.

7. Model retirement

This is the final phase of a machine learning model’s lifecycle. Just like human beings—when we get older, we retire from our job or business.

Similarly, when a model becomes outdated or the data it was trained on is no longer effective, it may fail to make accurate decisions or predictions in the current situation.

In such cases, we need to retire the model to avoid unnecessary resource utilization.

References:

What Is Machine Learning? What I Learned.

Nowadays, we are surrounded by various AI and machine learning technologies, many of which we use directly or indirectly.

If you use Google or any other search engine to get here, that’s an example.

YouTube, Netflix, Amazon recommendations, self-learning cars, face lock on devices, autocorrect features, and many more.

However, everything started from a thought

Can machines think? —a question posed by Alan Turing, a British mathematician—sparked the beginning of artificial intelligence.

Later, Arthur Samuel, the father of machine learning, created the first machine learning program that taught itself by playing games.

Yes — that’s where it all began.

okay,  what is actually Machine Learning?

What Is Machine Learning?

what is machine learning?
Just like the name says, machines try to learn from data and make decisions. It’s actually like imitating us.

In our childhood, we learned to recognize cats or dogs by seeing them many times.

When we see them again, we understand whether it’s a cat or a dog. The images we saw are stored in our minds, and we compare new ones with our memory. Similarly, machines also learn from data and try to identify or predict things, just like we do.

In the real world, a good example is unlocking a mobile with face scanning. When your phone captures your face for the first time, it stores the image and extracts features like nose shape or jawline, converting them into numbers.

Later, when you try to unlock it, the phone compares your live face with the stored data. If the match is above a certain threshold, it unlocks the phone — saying, “It’s you.”

Machine learning flutter

So, what is data? Anything that carries enough information to help a machine learn and make decisions can be called data.

For example, this blog post could be part of the training data for a model that explains machine learning. But to train a good model, you’d need many such blog posts — from different sources.

Similarly, articles, tweets, photos, audio clips, videos, medical records, and transactions — all of these are forms of data. If they carry useful information, they can be used in machine learning.

Based on the type of data and the way we train the model, machine learning is generally classified into four categories.
machine learning types

  1. Supervised Machine Learning
  2. Unsupervised Learning
  3. Semi – Supervised
  4. Reinforcement

Supervised Machine Learning

supervised machine learning labeled data

A machine learns from labeled data to make predictions — this is called Supervised Machine Learning.
Labeled data means the data comes with a label or description.

For example, you might provide a dog image labeled “dog” or an audio clip labeled “music.”
This helps the machine understand what the data represents.

An example algorithm used in supervised learning is Linear Regression, which can be used to predict house prices.

Unsupervised Learning

This is the opposite of Supervised Learning. It uses only data — no labels or descriptions.
Here, we don’t tell the machine what to learn.

So, the machine needs to find patterns or groups within the data on its own.
For example, K-Means Clustering is an algorithm used for customer segmentation (grouping users based on behavior for targeted marketing).

Semi-Supervised Machine Learning

In this type, the machine is trained with a small amount of labeled data and a large amount of unlabeled data.

Semi-Supervised Machine Learning = Low volume of labeled data + Large volume of unlabeled data.
Example: Self-training + Logistic Regression

Reinforcement Learning

It’s like training a dog. If you tell it to sit and it does, you give it a cookie. Otherwise, no cookie. Just like that, a machine learns by trial and error to reach a specific goal — by getting rewards or not getting them.

eg: Self driving car uses reinforcement learning to improve their driving skills.

That’s all for today.
will be back.

5 Ways To Get Instance Of ViewModel In Android

Creating viewmodel instance is needed if you are using MVVM architecture. Otherwise, MVVM is incomplete.  So in this post, I will tell you about different ways for creating instance of ViewModel in activity or fragment.

By using correct usage of viewmodel, we can avoid ‘Android cannot create instance of viewmodel’ issue also.

okay, let’s start.

First I will tell you in short. So it will save your time.

  1. viewModel() – Used in Jetpack Compose.
  2. by viewModels() – Apply it with Activity or fragment.
  3. by activityViewModels() – Recommended to use when multiple fragments need to share same data and has same instance of Activity
  4. Using ViewModelProvider – old way but still works.
  5. using ViewModelProvider.Factory –  Make use of it if you need to pass arguments to viewmodel.
  6. @hiltViewModel – This is from Hilt dependency injection, very helpful if you are using Hilt.
    • hiltViewModel() – Use it in Composables

Below, I have mentioned versions of different dependencies, so if you need different version, please check the maven repository and use the latest one.

Detailed Version With Code

  1. viewModel()

In Jetpack Compose, viewModel() delegate can be used for creating instance of viewmodel. But before that you need to include the dependencies in gradle file, only then you can use this. If you want to pass parameters, then go with Hilt or ViewModelProvider.Factory


androidx.Lifecycle:lifecycle-viewmodel-compose:"latest version"(2.8.7 )

2.  by viewModels()

val viewModel: MyViewModel by viewModels()

If you are using XML based approach, you can easily create instance of viewmodel using viewModels(). This does not support passing parameters.

3. activityViewModels()

val viewModel: MyViewModel by activityViewModels()

You can use this in your fragment to access instance of viewmodel – better to use when multiple fragment within same activity needs viewmodel instance.

implementation("androidx.fragment:fragment-ktx:1.6.2")

4. Use ViewModelProvider

ViewModelProvider(this).get(MyViewModel::class.java)

As the name suggests ViewModelProvider gives the viewmodel instance by passing class type of the viewmodel.
5. ViewModelProvider.Factory

val repository = MyRepository()
val factory = MyViewModelFactory(repository)
viewmodel = ViewModelProvider(this, factory)[MyViewModel::class.java]

In most cases, we need to pass a repository or other instances to the viewmodel. So in this example, i am passing a repository to the viewmodel using ViewModelProvider.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

class MyViewModelFactory(private val repository: MyRepository) :ViewModelProvider.Factory{
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if(modelClass.isAssignableFrom(MyViewModel::class.java)){
         return MyViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }

}

Here, the subclass of ViewModelProvider.Factory will receives the instance of repository and creates viewmodel instance for you.

5. Using @HiltViewModel

This approach can be used if you are Hilt dependency injection in your project. But you need to do some changes here, not easy like above steps,

1. You need to add dependency in gradle file.
2. Define subclass of Application and annotate with @HiltAndroidApp.
3. Annotate viewmodel class with @HiltViewModel.
4. if you want to access instance of viewmodel in activity or fragment, annotate those with @AndroidEntryPoint


  //  id 'com.google.dagger.hilt.android' version '2.48' apply false

   // Dagger - Hilt
    implementation "com.google.dagger:hilt-android:2.48"
    kapt "com.google.dagger:hilt-android-compiler:2.48"
    kapt "androidx.hilt:hilt-compiler:1.0.0"

  • These are the dependencies you need to add in gradle file.
@HiltAndroidApp
class MyApplication: Application()
  • Create a subclass of Application like above and Use @HiltAndroidApp annotation.

@HiltViewModel
class MainViewModel @Inject constructor(
    private val repository: Repository,
    application: MyApplication
): AndroidViewModel(application)

  • If there is any parameters need to pass, create a module and pass from there. So internally hilt will manage. Use @Inject to injecting dependencies through constructor.
@AndroidEntryPoint
class MyFragment : Fragment() {

    private val mainViewModel: MainViewModel by viewModels()


hiltViewModel() - call in composable if you are using hilt.

  • Access like above your viewmodel, do not forget to annotate activity or fragment with @AndroidEntryPoint where you are calling viewmodel.

This is for now, may be I will update later.
Thanks.

Color.kt vs colors.xml : Which is better for Jetpack Compose?

From the arrival of Jetpack Compose, developer can store and access color values in 2 ways.

i. Color.kt – Modern approach.
ii. XML – Traditional approach.

both methods are acceptable in jetpack compose.

but which one is better ?

It actually depends on the scenario.

i. For New Jetpack Compose projects

Here, Its better to store colors in Color.kt because its more efficient than resolving xml resources by id. Additionally it provides type safety and IDE can automatically suggest colors.

Using this approach, we can assign different color for light and dark theme. If you are making a multiplatform project. recommended to use this approach.

color kt file location
You can easily found the file in app/src/main/java/com/userName/packagename/ui/theme/Color.kt

val Colors.topAppBarBackgroundColor:  Color
    @Composable
    get() = if(isSystemInDarkTheme()) Color.Black else Color.White
  • Above code, just implementing dark and light theme based on the isSystemInDarkTheme() method.

ii. Projects with XML + Jetpack compose

In this situation, you can store color values in colors.xml file. So both views and composable can easily access from a central location.

For implementing Dark theme, you can make use of night mode of colors.xml.
colors.xml file location
Colors.xml file can be found in app/src/main/res/values/colors.xml.

val appBarBackgroundColor = colorResource(R.color.topAppBarBackgroundColor)

Summmary

Users can still store color values in both files. However for Jetpack Compose, the preferred approach is storing color values in Color.kt file which make IDE to suggest and assures type safety. But if you are working on a project with both Jetpack Compose and XML, you can store values in colors.xml as the traditional way.

Whatever it is, try to store all color code in one file for easy access and maintenance.

3 Things You Must Need To Know : Jetpack Compose vs XML

Let’s compare Jetpack Compose vs XML.

Before that I need to tell you something.

When Kotlin arrived, I searched the whole internet to decide: should I learn Kotlin or not?
Back then, some posts convinced me that learning Kotlin would give me a strong advantage as an Android developer.

And they were right.

Now, for anyone searching the internet and wondering whether to learn Jetpack Compose, here’s my answer:

1. Performance

live edit in jetpack compose vs XML
I will start with my favorite part about Jetpack Compose – Live edit.

Why its my favorite?

This one really improved my productivity.

If you did a simple layout change,You dont need to restart the whole application, it just reloads direct in your emulator or real devices. But it still evolving, so sometimes it faces issues with larger projects.

XML lacks this feature due to its imperative UI paradigm and Android view system.

Language Support

Jetpack compose is defined for Kotlin, so if you want to use compose, then you need to write kotlin code. As for now, i don’t seem any plan with java.

XML works well with both languages, so choice of language is not a barrier.

Rendering layouts

When it comes to rendering layouts, XML perform better for static layouts, but less efficient for complex layouts, because findViewById and binding calls make difficult. But compose is better for complex UIs because it only renders the specific part of the UI that needs to be changed.

Resource Utilization

XML need more effort when rendering complex layout ui. on the other side Jetpack Compose efficiently manage recompositions, but triggering unnecessary recomposition can lead to inefficiencies.

Preview support

Both have built in preview support in Android Studio.
In XML, android studio – we can easily drag and drop our views wherever we want. it make begginer effort less. So that doesn’t end here. Compose also has a nice preview system, renders preview more efficiently than XML.

2. Support

Community

Jetpack Compose is relatively new, but its community is growing day by day. But for XML, already a huge community out there. as you know, it comes from api level 1. So most of the code are around with XML. Most of the questions you will face will already answered by someone in stackoverflow, reddit or any other site in google. compose not in a long way, they also quickly closing the gap.

Devices Support

Jetpack Compose will not work below api level 21(lolipop), to support running below api 21, then you need to use XML. But however, number of running devices below api 21 is very low. If you are migrating from XML to Compose. sometimes, it might be difficult for larger projects. so you can go for a hybrid approach. such as using compose code in xml.

Using composeView, you can add compose inside XML.

3. Learning curve

i. Beginner

If you are new to android, learning curve for Jetpack Compose feels natural. if you are a beginner in android, but also familiar with Flutter or react native, then it will reduce the intensity of your learning process. However XML may seem easy at first glance, you can quickly understand each tag and its properties, how they work.

XML has abundance of tutorials, books and documentation, making it sufficient for beginner to learn. For compose, developers are creating more tutorials and vlogs, which increases the resources and reduce the gap.

ii. Already an android developer

It become moderate to you, if you are learning compose and also compose not that much documentation or abundance of tutorials out there. So sometimes, you may need to troubleshoot some issues your self.

for XML, there is lot of boilerplate code, also need to switch to java/kotlin code for functionality. For compose, that you can simply do in Kotlin, but must have a better knowledge in Kotlin.

Jetpack Compose vs XML – Summary

Its better to start learning Jetpack compose because that’s the future and it also make app development more productive. But still XML is in the ground, so you can not avoid that. if you are a beginner, most of the projects are in xml, its better to learn xml first, but many companies also hire people with compose due to new projects. so final part, its beneficial to know the basics of xml and go for Jetpack Compose.

Kotlin For loop with Index example

Hi, Welcome to AndroidRide!.

Let’s learn about Kotlin for loop with index.

For loop with indices property

In this simple example, we will use indices property of collections to get the index.

    val items = listOf("A","B", "C")

    for(index in items.indices){
        println("indices: $index, item: ${items[index]}")
    }


kotlin for loop with index

  • Here, indices property returns 0..2 (IntRange)
  • using indices and string template interpolation, we can take data from items list and display like shown above.
  • Better to use indices, if you only need the index.
  • You can use the indices property with arrays and strings to access their indices. However, it doesn’t work with maps or sets since they are not indexed.

For loop with string value

In this section, we can use indices property with string value.

 val strValue = "String"
        for(i in strValue.indices){
            println("index: $i, char: ${strValue[i]}")
        }

kotlin-for-loop-indices-with-string-value.png

  • Each character’s index will be iterated, and using the index, we can access and display the corresponding character.

ArrayList with index example

Kotlin arraylist helps to store data in dynamic array.

    val arrayListItems = arrayListOf("Item 1", "Item 2", "Item 3")
        for(index in arrayListItems.indices){
            println("ArrayList with index: ${arrayListItems[index]}")
            }

kotlin-for-loop-arraylist-with-index

  • just like above examples, indices property returns 0..to size of the arraylist – 1.

Using withIndex() method

If you need both the index and the item while iterating, use withIndex().

 val char = arrayOf("a", "b", "c")
    for ((index, ch) in char.withIndex()) {
        println("Index: $index, character: $ch")
    }

kotlin-for-loop-withIndex

  • In this section, arrayOf() creates an array with 3 characters.
  • withIndex() returns IndexedValue which gives index and value.

    Complete Source Code

    package com.androidride.kotlin
    
    fun main() {
    
        val items = listOf("A", "B", "C")
        for (index in items.indices) {
            println("indices: $index, item: ${items[index]}")
        }
    
        val strValue = "String"
        for (i in strValue.indices) {
            println("index: $i, char: ${strValue[i]}")
        }
    
        val arrayListItems = arrayListOf("Item 1", "Item 2", "Item 3")
        for (index in arrayListItems.indices) {
            println("ArrayList with index: ${arrayListItems[index]}")
        }
    
        for ((index, item) in items.withIndex()) {
            println("withIndex: index: $index, item: $item")
        }
    
    }
    
    
    
  • Android WebView Tutorial
  • Kotlin control flow docs

Please add star to AndroidRide repository, if you like.
Please share with your friends and family.

Kotlin For each tutorial : 9 Examples

In this tutorial, you’ll learn how to use Kotlin’s forEach higher-order function.

When we need to iterate over an array or list to search for or filter specific data, the traditional for loop is often used. However, in Kotlin, there’s a more functional and concise approach—the forEach function.

Let’s create a simple example using forEach.

Simple forEach Example in Kotlin

val list = listOf(1, 2, 3)

    list.forEach { item ->
        println(item)
    }


kotlin list foreach

  • In this example, the listOf function creates a simple list.
  • using the forEach function, each item will be iterated.
  • The it keyword is used for the current item. In the first iteration, it contains the value 1, in the second iteration, it becomes 2, and in the final iteration, it holds the value 3.
  • Each value prints to the terminal

Range with forEach

In this part, we can use range with forEach. In kotlin, range means sequence of values defined between start value and end value.

Sometimes, you don’t need to create a list. You can use a range directly like below, which is more memory-efficient.

(1..3).forEach {
        println(it)
    }

range foreach kotlin

  • Above, we have a range that contains the values 1,2, and 3.
  • Each element is printed in the terminal one by one.

Using forEach with a string

If you’re a beginner, you may encounter coding questions in interviews such as counting characters in a string. in these situations, forEach function can be quite useful.

val charArray = "String"
    charArray.forEach {
        println(it)
    }

Using forEach with a string

  • In this section, forEach treats String as character array. So each character in string will be iterated over.

Using forEach with array

val array = arrayOf("a","b","c")
    array.forEach {
        println("array : $it")
    }


array foreach kotlin

  • Just like list, we can use array.
  • it is the current item.

Using forEach with Maps

  
    val map = mapOf(1 to "a", 2 to "b", 3 to "c")

    map.forEach{ (key, value) ->
        println("Key: $key -> Value: $value")
    }

map foreach kotlin

  • In this case, mapOf create a simple map, making numbers 1, 2, and 3 the keys and “a”, “b”, and “c” the values.
  • Unlike lists, when you use forEach with maps, the lambda expression provides the key and value as parameters.
  • This allows you to display your data effectively.

Using forEachIndexed with list

forEach, which comes with an index, is called forEachIndexed.

If you are creating a list and need to display each item with its index, you can use this higher-order function.

val list = listOf(1, 2, 3)
 list.forEachIndexed { index, item ->
        println("Index: $index, Item: $item")
    }

list forEachIndexed

  • This part, you will receive index along with item.
  • If you don’t need index, simply use forEach.

Using forEachIndexed with map

val map = mapOf(1 to "a", 2 to "b", 3 to "c")
  map.entries.forEachIndexed{ index, item ->
        println("Index: $index, Key: ${item.key} -> Value: ${item.value}")
    }

  • You can’t directly use forEachIndexed on a map.
  • Like shown above, you need to use entries property to get a set of key/value pairs from map.

map forEachIndexed

forEach – continue functionality

You can use continue statement directly in a for loop, but you cannot use it directly in forEach.

val list = listOf(1, 2, 3)

 list.forEach {
        if(it==2){
            println("Skips the second iteration")
            return@forEach
        }

        println(it)
    }

foreach continue kotlin

  • Use return@forEach to stop the current iteration and continue with the next one in the loop.

forEach – break functionality

val list = listOf(1, 2, 3)

  run loop@{
        list.forEach {
            if(it==2){
                println("Skips iterations from here")
                return@loop
            }

            println(it)
        }
    }
  • Use return@loop break out of the forEach loop.

break foreach kotlin

Complete Source Code

package com.androidride.kotlin

fun main() {

    val list = listOf(1, 2, 3)

    println("simple list - forEach example")
    list.forEach {
        println(it)
    }

    println("range with foreach")
    (1..3).forEach {
        println(it)
    }

    println("string with foreach")
    val charArray = "String"
    charArray.forEach {
        println(it)
    }

    println("array with foreach")
    val array = arrayOf("a","b","c")
    array.forEach {
        println("array : $it")
    }

    println("map with foreach")
    val map = mapOf(1 to "a", 2 to "b", 3 to "c")

    map.forEach{ (key, value) ->
        println("Key: $key -> Value: $value")
    }

    println("forEachIndexed with lists")
    list.forEachIndexed { index, item ->
        println("Index: $index, Item: $item")
    }

    println("forEachIndexed with maps")
    map.entries.forEachIndexed{ index, item ->
        println("Index: $index, Key: ${item.key} -> Value: ${item.value}")
    }

    println("forEach - break functionality")
    run loop@{
        list.forEach {
            if(it==2){
                println("Skips iterations from here")
                return@loop
            }

            println(it)
        }
    }

    println("forEach - continue functionality")
    list.forEach {
        if(it==2){
            println("Skips the second iteration")
            return@forEach
        }

        println(it)
    }

}

Render List Of Row Or ListView Inside Column in Flutter

In this post, you will learn how to render a list of rows or a ListView inside a Column. When implementing a ListView inside a Column, you might encounter errors. Using the examples below, you can understand how to avoid them.

Let’s get started.

In this first example, I will implement list of row texts inside Column.

List of Row Inside A Column Example – I

list of row inside column in flutter

  • I have used a For loop to generate Row’s childrens.
  • The for loop creates 50 rows inside the Column, if it exceeds the screen height. You will get the renderflex errors.
  • To avoid yellow & black renderflex overflow errors, You can use ListView or SingleChildScrollView around the Column.
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: 'List of Row Inside A Column',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('List of Row Inside A Column'),
        ),
        body: 
        // SingleChildScrollView(
        //   child: 
          Column(
            children: [
              for (int i = 1; i <= 50; i++)
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'text $i',
                      style: const TextStyle(
                        fontSize: 18,
                      ),
                    ),
                    const SizedBox(
                      width: 20,
                    ),
                    Text(
                      'content $i',
                      style: const TextStyle(
                        fontSize: 18,
                      ),
                    ),
                  ],
                ),
            ],
          ),
        //),
      ),
    );
  }
}

List of Row Inside a Column in Flutter - II

flutter render list of row inside column
This example is really useful for those who are making form inside a column. Here, I have used a TextField inside Row.

If you are making any login or signin form, recommended to use Form and TextFormField.

  • You must aware that TextField or TextFormField inside a Row can create InputDecorator unbound width error. This is due to TextFormField does not have intrinsic width (natural width), and row wants it's childs intrinsic size and that's makes the problem
  • So either Use Expanded, Flexible or SizedBox with width property around the TextField or TextFormField.
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: 'List of Row Inside A Column',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('List of Row Inside A Column'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              for (int i = 1; i <= 50; i++)
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [
                    SizedBox(width: 10),
                    Text('Name : '),
                    SizedBox(width: 10),
                    Flexible(
                      child: TextField(
                        decoration: InputDecoration(hintText: 'name'),
                      ),
                    )
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}


How to use ListView inside Column In Flutter?

When you place ListView inside column, it ends with an exception most of the time. because both ListView and Column tries to expand in the main axis direction (here I am talking above Vertical direction). Flutter needs to know how much space ListView and Column needed.

Using Expanded

listview inside column using expanded

  • Use Expanded widget around the ListView - Recommended.
  • It expands the listview to take the available space inside the column.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Inside Column Using Expanded'),
        ),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: const Text(
                'ListView Inside Column Using Expanded',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ),
            Expanded(
              child: ListView(
                padding: EdgeInsets.all(8),
                children: [
                  for (int i = 0; i < 50; i++)
                    Align(
                      alignment: Alignment.center,
                      child: Text('Item $i'),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Using shrinkWrap property

flutter render list of row inside column

  • By setting, shrinkWrap:true, ListView will take as much as space only the children needed.
  • Actually, it will compute the size of the entire content in ListView.
  • But setting shrinkWrap:true can make performance hit. So avoid it as much as you can.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Inside Column Using shrinkWrap Property'),
        ),
        body: Column(
          children: [
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                'ListView Inside Column Using shrinkWrap Property',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ),
            ListView(
              shrinkWrap: true,
              padding: EdgeInsets.all(8),
              children: [
                for (int i = 0; i < 30; i++)
                  Align(
                    alignment: Alignment.center,
                    child: Text('Item $i'),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Using SizedBox

flutter render list of row inside column

  • Use SizedBox around the ListView with a specific height value.
  • Height of the listview turns to SizedBox height.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Inside Column Using SizedBox'),
        ),
        body: Column(
          children: [
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                'ListView Inside Column Using SizedBox',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ),
            SizedBox(
              height: 500,
              child: ListView(
                padding: EdgeInsets.all(8),
                children: [
                  for (int i = 0; i < 50; i++)
                    Align(
                      alignment: Alignment.center,
                      child: Text('Item $i'),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}



That's all for now. If you like this post, please share it with your family and friends.
Thanks.

3 Ways To Change Elevated Button Color In Flutter

Do you want to change color of Elevated Button?

Then you are in the right place.

So let’s start with a simple example.

Most of the time, this is the one you really needed.

How To Change Elevated Button Color?

change elevatedbutton color

  • Use style property of ElevatedButton and pass ElevatedButton.styleFrom().
  • Inside, ElevatedButton.styleFrom(), give primary parameter and color as value.
  • You can use onPrimary property to change Text Color of ElevatedButton.

ElevatedButton(
                  child: const Text('ElevatedButton'),
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    primary: Colors.deepOrangeAccent,
                    //onPrimary: Colors.black,
                  ),
                ),

How To Change Elevated Button Color Using Theme?

elevated button color change using theme widget
Sometimes you need to set same color and text color for a group of ElevatedButtons used in a form or section. You don’t need to use style property for each one. In these situations, You can use Theme widget.

  • This example, I have used Column for holding two ElevatedButton and the Column is wrapped with Theme Widget.
  • Theme widget provides elevatedButtonTheme property to set our style.
  • You need to specify with ElevatedButtonThemeData object and style values.
  • It affects all the children inside of it.

Theme(
                  data: ThemeData(
                    elevatedButtonTheme: ElevatedButtonThemeData(
                      style: ElevatedButton.styleFrom(
                        onPrimary: Colors.white,
                        primary: Colors.green,
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      ElevatedButton(
                        child: const Text('ElevatedButton 1'),
                        onPressed: () {},
                      ),
                     const SizedBox(
                        height: 10,
                      ),
                      ElevatedButton(
                        child: const Text('ElevatedButton 2'),
                        onPressed: () {},
                      ),
                    ],
                  ),
                )

How To Change Elevated Button Color Using Theme – App level

  • Using this MaterialApp theme property, you can change all ElevatedButton color in your app with simple piece of code.
  • You should give ThemeData object and elevatedButtonTheme property value should be ElevatedButtonThemeData

return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ElevatedButton Color Change Example',
      theme: ThemeData(
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            primary: Colors.red,
          ),
        ),
      ),

Complete Source Code

elevated button color flutter

  • In this, main example, I have used 3 different ways mentioned above in this post.
  • First example uses the color given by App theme data. So it chooses, Red color.
  • Second, ElevatedButton overrides app level theme color by using its own style. So here, ElevatedButton uses Orange color and also black for text color.
  • Third one, we have used Theme Widget, using that you can change color of all the children (ElevatedButton)inside of Theme Widget.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ElevatedButton Color Change Example',
      theme: ThemeData(
        //primarySwatch: Colors.red,
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            primary: Colors.red,
          ),
        ),
      ),
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Flutter ElevatedButton Color Change Example'),
          ),
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
        //It uses applevel theme color
        ElevatedButton(
                  child: const Text('ElevatedButton'),
                  onPressed: () {},
                ),
//Here It uses own style color by overriding app level color.
                ElevatedButton(
                  child: const Text('ElevatedButton'),
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    primary: Colors.deepOrangeAccent,
                    onPrimary: Colors.black,
                  ),
                ),
//Here, Theme provides color for the ElevatedButton.
                Theme(
                  data: ThemeData(
                    elevatedButtonTheme: ElevatedButtonThemeData(
                      style: ElevatedButton.styleFrom(
                        primary: Colors.green,
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      ElevatedButton(
                        child: const Text('ElevatedButton 1'),
                        onPressed: () {},
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      ElevatedButton(
                        child: const Text('ElevatedButton 2'),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

If you like this post, please share it with your family and friends.
Thanks.