Rounded Corners Image in Flutter

In this tutorial, we’ll look at just one of Flutter’s numerous image display options.

In particular, we will discover how to produce an image with rounded corners, a preferred design feature in contemporary mobile applications.

It’s crucial to realise that Flutter provides a variety of choices for showing images before moving on to the main topic. There are several widget classes available for each use scenario, and you can decide whether to display an image from a local file or a network URL.

In this tutorial, we’ll concentrate on obtaining a picture from a remote URL.

You may use the ClipRRect widget to clip an image with rounded rectangle corners in Flutter to give it rounded corners.

Additionally, you can utilise that widget as a Container to make handling images with height and width simple.

Here is syntax of the ClipRRect widget

ClipRRect(
  borderRadius: BorderRadius.circular(10.0), // Adjust the value to change the corner radius
  child: Image.network(
    'https://example.com/image.jpg', // Replace with your image URL
    width: 200, // Adjust the width as needed
    height: 200, // Adjust the height as needed
    fit: BoxFit.cover,
  ),
)

The borderRadius parameter in Flutter functions precisely the same way it does in CSS, so long as you are familiar with that language.

You can use shorthand notation to set various values for each corner or set the borderRadius to a specified number.

To begin your Dart file, don’t forget to import the required Flutter packages:

import 'package:flutter/material.dart';

Here it is example of that code.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var title = 'Main App Images';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Image.network(
          'https://example.com/image.jpg', // Replace with your image URL
          fit: BoxFit.cover,
        ),
        ),
      ),
    );
  }
}

The image will have rounded corners when presented by surrounding the Image widget with ClipRRect.

A checkboxlisttile in Flutter

Flutter comes with a built-in widget called CheckboxListTile. We may describe it as a CheckBox and ListTile combo. As with the CheckBox widget, it has attributes like value, activeColor, and checkColor, whereas the ListTile widget has properties like title, subtitle, and contentPadding.

To Google the checkbox, we may tap anywhere on the CheckBoxListTile. All the attributes of this widget are listed below, along with an illustration.

Below is the Checkboxlisttile’s syntax.

CheckboxListTile(
{Key key,
@required bool value,
@required ValueChanged onChanged,
Color activeColor,
Color checkColor,
Widget title,
Widget subtitle,
bool isThreeLine: false,
bool dense,
Widget secondary,
bool selected: false,
ListTileControlAffinity controlAffinity: ListTileControlAffinity.platform,
bool autofocus: false,
EdgeInsetsGeometry contentPadding,
bool tristate: false}
)

Here is the example of CheckBoxListTile. In this illustration, we create a listview with every checkbox. Make a model for that listview as well. It is a checkbox dynamic listing of data.

CheckBoxListTileDemo.dart

class CheckBoxListTileDemo extends StatefulWidget {
  @override
  CheckBoxListTileDemoState createState() => new CheckBoxListTileDemoState();
}

class CheckBoxListTileDemoState extends State<CheckBoxListTileDemo> {
  List<CheckBoxListTileModel> modelCheckBoxListTile =
      CheckBoxListTileModel.getUsers();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: new Text(
          'CheckBox ListTile Demo App',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: new ListView.builder(
          itemCount: modelCheckBoxListTile.length,
          itemBuilder: (BuildContext context, int index) {
            return new Card(
              child: new Container(
                padding: new EdgeInsets.all(10.0),
                child: Column(
                  children: <Widget>[
                    new CheckboxListTile(
                        activeColor: Colors.pink[300],
                        dense: true,
                        //font change
                        title: new Text(
                          modelCheckBoxListTile[index].title,
                          style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              letterSpacing: 0.5),
                        ),
                        value: modelCheckBoxListTile[index].isCheck,
                        secondary: Container(
                          height: 50,
                          width: 50,
                          child: Image.asset(
                            modelCheckBoxListTile[index].img,
                            fit: BoxFit.cover,
                          ),
                        ),
                        onChanged: (bool? val) {
                          setState(() {
                            modelCheckBoxListTile[index].isCheck = val!;
                          });
                        })
                  ],
                ),
              ),
            );
          }),
    );
  }

  void itemChange(bool val, int index) {
    setState(() {
      modelCheckBoxListTile[index].isCheck = val;
    });
  }
}

class CheckBoxListTileModel {
  int userId;
  String img;
  String title;
  bool isCheck;

  CheckBoxListTileModel(
      {required this.userId,
      required this.img,
      required this.title,
      required this.isCheck});

  static List<CheckBoxListTileModel> getUsers() {
    return <CheckBoxListTileModel>[
      CheckBoxListTileModel(
          userId: 1,
          img: 'assets/images/local1.png', // Need to change here Asset Image Name
          title: "JAVA",
          isCheck: true),
      CheckBoxListTileModel(
          userId: 2,
          img: 'assets/images/local2.jpeg', // Need to change here Asset Image Name
          title: "Angular JS",
          isCheck: false),
      CheckBoxListTileModel(
          userId: 3,
          img: 'assets/images/local3.webp', // Need to change here Asset Image Name
          title: "Flutter ",
          isCheck: false),
      CheckBoxListTileModel(
          userId: 4,
          img: 'assets/images/local4.png', // Need to change here Asset Image Name
          title: "Kotlin",
          isCheck: false),
      CheckBoxListTileModel(
          userId: 5,
          img: 'assets/images/local5.png', // Need to change here Asset Image Name
          title: "PHP",
          isCheck: false),
    ];
  }
}

You may have observed that this Checkbox implementation method uses less code. When this code is executed, a list of alternatives with checkboxes is displayed. A checkbox’s state can be changed by tapping on it, and the modelCheckBoxListTile will be modified as a result.

How can I change a Checkbox’s Color?

Using the activeColor and checkColor parameters of the Checkbox widget, Flutter users can alter the colour of a Checkbox.

The checkbox’s colour while it is checked can be changed using the activeColor property, and the checkmark’s colour can be changed using the checkColor property. Here is an illustration of how to apply these attributes:

Checkbox(
  value: true,
  onChanged: (newValue) {
    // Do something
  },
  activeColor: Colors.blue, // Change the color of the checkbox when it is checked
  checkColor: Colors.white, // Change the color of the checkmark inside the checkbox
)

The checkbox’s colour changes to blue when it is checked in the example above since the activeColor attribute is set to Colors.blue. Like this, the checkmark inside the checkbox transforms to white when the checkColor attribute is set to Colors.white.

Checkbox Example In Flutter

Users can choose several alternatives from a list of possibilities by using checkboxes, which are a key component of user interfaces. We will look at creating checkboxes in Flutter and managing state changes in this blog article. All other widgets, including containers, list views, and others, can use checkboxes.

Using Checkbox class properties, we may change the colors, and also listen to the state changes.

Checkbox Demo

Checkbox(  
  value: this.showvalue,   
  onChanged: (bool value) {  
    setState(() {  
      this.showvalue = value;   
    });  
  },
),

Creating a Checkbox

In Flutter, we can utilise the Checkbox widget to construct a checkbox. Let’s begin by configuring a straightforward Flutter application and making a checkbox:

import 'package:flutter/material.dart';

class CheckboxExample extends StatefulWidget {
  @override
  _CheckboxExampleState createState() =&gt; _CheckboxExampleState();
}

class _CheckboxExampleState extends State<checkboxexample> {
  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkbox Example'),
      ),
      body: Center(
        child: Checkbox(
          value: _isChecked,
          onChanged: (bool newValue) {
            setState(() {
              _isChecked = newValue;
            });
          },
        ),
      ),
    );
  }
}

Checkboxes are essential elements for enabling users.

ConstraintLayout Example In Android

Android’s ConstraintLayout layout manager is strong and adaptable, enabling you to design intricate and responsive user interfaces.

It enables you to specify restrictions (relationships) across views so they can adjust to various screen sizes and orientations.

ConstraintLayout is a popular option for creating intricate and dynamic user interfaces since it performs better than nested layouts like RelativeLayout and LinearLayout.

Let’s look at an example of a login screen to see how ConstraintLayout is used. Let’s say we have a layout with a login button, two EditText fields for the user name and password, and more.

The ConstraintLayout must first be included to our XML layout file as the root element. The restrictions for each view can then be specified within the ConstraintLayout.

Here is the XML File of the layout.

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/usernameEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Username"
        android:inputType="text"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.7"
        />

    <EditText
        android:id="@+id/passwordEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintTop_toBottomOf="@+id/usernameEditText"
        app:layout_constraintStart_toStartOf="@id/usernameEditText"
        app:layout_constraintEnd_toEndOf="@id/usernameEditText"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.7"
        app:layout_constraintVertical_bias="0.2"
        />

    <Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        app:layout_constraintTop_toBottomOf="@+id/passwordEditText"
        app:layout_constraintStart_toStartOf="@id/passwordEditText"
        app:layout_constraintEnd_toEndOf="@id/passwordEditText"
        app:layout_constraintVertical_bias="0.2"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

We would set the login button’s top constraint to the bottom of the password field and its horizontal constraint to the centre horizontally in order to centre it and align it below the password field.

To fine-tune the positioning and behaviour of the views within the ConstraintLayout, we may also declare other constraints such as margin, aspect ratio, visibility, and more.

These limitations ensure that the views automatically alter their sizes and locations in response to changes in screen size or device usage.

Finally, ConstraintLayout offers an adaptable and effective method for creating responsive user interfaces in Android. You may design layouts that adjust to different screen sizes and orientations by specifying relationships between views.

Relative Layout Example In Android

One of the most used layout managers in Android programming is RelativeLayout.

It offers a versatile technique to position UI items in relation to one another or to the parent container. This enables the development of intricate and dynamic user interfaces.

Each view in a RelativeLayout is placed according to how it relates to other views.

Several properties, including alignParentTop, alignParentBottom, alignLeft, alignRight, and others, are used to do this. We can design user interfaces (UIs) that adjust to various screen sizes and orientations by establishing these relationships.

Let’s look at an example to see how RelativeLayout is used. Consider a straightforward form that consists of a TextView, an EditText, and a Button. The TextView and Button should be positioned above and below the EditText, respectively.

Implementation in XML:
To utilize RelativeLayout, define it in XML layout files using the following syntax:

<RelativeLayout
    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:padding="16dp"
    tools:context=".MainActivity">

    <!-- All Child views here -->

</RelativeLayout>

This may be done by giving each view in the RelativeLayout the proper layout properties.

The views will be dynamically positioned based on their relationships by utilising these layout parameters. This implies that the other views would automatically adjust if we were to modify the size or position of any view.

In Relative layout we can use other child view like Linearlayout or constrain layout or many other options.

RelativeLayout is especially flexible and gives a wide range of options.

RelativeLayout allows you to centre an element on the screen, centre it on the left, centre it in the middle of the screen, and more.

Because every child view is drawn by default at the top-left of the layout, you must specify each view’s location using one of the available layout attributes.

Linearlayout Example In Android

Android’s LinearLayout, a versatile ViewGroup subclass, offers developers an efficient and intuitive way to arrange child View elements in a linear fashion. You can check Linearlayout Example in Android Project.

By leveraging the orientation property, LinearLayout facilitates seamless organization of child views either horizontally or vertically. With its ability to create single or multi-row, multi-column layouts, LinearLayout proves to be an indispensable tool for crafting dynamic and visually appealing user interfaces.

All the child elements arranged one by one in multiple rows and multiple columns And you can create Userfriendly UI.

Horizontal list: One row, multiple columns.
Vertical list: One column, multiple rows.

Advantages of LinearLayout:

  1. Simplicity: LinearLayout provides a straightforward and intuitive approach to arranging child views in a linear manner, reducing the complexity of UI development.
  2. Flexibility: Developers have the freedom to adjust the orientation as needed, allowing for adaptable and responsive layouts based on the specific requirements of the application.
  3. Dynamic Layouts: LinearLayout enables the creation of dynamic UIs by dynamically adding or removing child views at runtime.
  4. Efficient Resource Utilization: LinearLayout consumes minimal system resources, ensuring smooth performance and efficient memory management.

Implementation in XML:
To utilize LinearLayout, define it in XML layout files using the following syntax:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- All Child views here -->

</LinearLayout>

Android’s LinearLayout empowers developers to effortlessly create dynamic and well-structured user interfaces.

Its ability to arrange child views linearly, either horizontally or vertically, provides the foundation for crafting visually appealing and user-friendly layouts.

You can also check Edittext Example and Textview Example layout on XML File.

Practical Usage Scenarios:

  1. Navigation Bars: LinearLayout simplifies the construction of horizontal or vertical navigation bars, ensuring consistent spacing and alignment of navigation elements.
  2. Form Input Fields: By organizing form input fields vertically, LinearLayout enhances user experience and readability.
  3. Image Galleries: By implementing a horizontal LinearLayout, images can be arranged side by side, creating visually appealing image galleries.

With LinearLayout’s simplicity, flexibility, and efficiency, developers can optimize resource utilization while delivering an exceptional user experience. By harnessing the power of LinearLayout, developers can unlock the potential for innovative and intuitive UI designs.

Container Tutorial with Examples – Flutter

Container classes in flutter are convenient ways to combine common painting, positioning, and sizing of widgets.

A container can be used to store one or more widgets and position them on the screen according to our convenience. Basically, a container is like a box to hold its contents. A basic container element that stores a widget has a margin, which separates it from other contents.

The total container can have a border of different shapes, for example, rounded rectangles, etc. A container surrounds its child with padding and then applies additional constraints to the padded extent (including the width and height)

Syntax of Container Class given below

Container({Key key,
           AlignmentGeometry alignment, 
           EdgeInsetsGeometry padding, 
           Color color, 
           Decoration decoration, 
           Decoration foregroundDecoration, 
           double width, 
           double height, 
           BoxConstraints constraints, 
           EdgeInsetsGeometry margin, 
           Matrix4 transform, 
           Widget child, 
           Clip clipBehavior: Clip.none});

Here’s an example of using the Container class in Flutter:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Container Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Container Example'),
        ),
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            padding: EdgeInsets.all(16),
            margin: EdgeInsets.all(16),
            alignment: Alignment.center,
            child: Text(
              'Hello, World!',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

The Container class in Flutter provides a flexible and powerful way to manage the layout and appearance of UI elements.

It allows you to control dimensions, alignment, padding, margin, background color, and more. With its wide range of properties and customization options, the Container class is an essential widget for creating attractive and well-structured Flutter UIs.

Edittext Implementation in Kotlin

Android EditText is a fundamental component that allows users to input and edit text within an application. In this blog post, we will explore the implementation of EditText in Android using the Kotlin programming language.

We will cover the essentials of working with EditText, including basic usage, input validation, event handling, and customization options, to create powerful text input experiences.

activity_main.xml

<RelativeLayout 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:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your text" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editText"
        android:layout_marginTop="16dp"
        android:text="Submit" />

</RelativeLayout>

MainActivity.kt

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var editText: EditText
    private lateinit var button: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        editText = findViewById(R.id.editText)
        button = findViewById(R.id.button)

        button.setOnClickListener {
            val inputText = editText.text.toString()
            showToast("Show this text: $inputText")
        }
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}

This is the basic example of Edittext in Android with Kotlin.

Validating user input is crucial for data integrity and app functionality. We’ll explore various validation techniques such as input type restrictions, length limitations, and regular expression-based validation.

We’ll also discuss how to handle invalid input and provide appropriate error messages to the user.

EditText is a powerful component that enables user input and text editing in Android applications. This blog post has covered the essentials of EditText implementation, including basic usage, input validation, event handling, customization, and advanced features.

TextView Implementation in Kotlin

Android app development, the TextView plays a crucial role in presenting textual information to the user. Whether it’s displaying static text, dynamic content, or even richly formatted text, the TextView is an indispensable user interface component.

A simple XML code of TextView in a layout is shown below.

mainactivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_view_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hi, How are you ?" />

</LinearLayout>

TextView supports multiline text display and provides options for controlling text wrapping and truncation.

We’ll demonstrate how to set the maximum number of lines, enable scrolling for long text, and implement ellipsis for text that exceeds the available space.

Additionally, we’ll explore the use of scrollable TextView containers for displaying large amounts of text. Now Please check below kotlin code.

MainActivity.kt

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView = findViewById(R.id.textView)

        val content = "Welcome to Kotlin TextView!"
        textView.text = content
    }
}

TextView is a powerful component that plays a crucial role in presenting text-based information in Android apps. By mastering its implementation, you can create visually appealing and interactive text displays.

This blog post has provided an overview of TextView basics, text formatting and styling, user interaction, multiline text handling, and accessibility considerations.

Armed with this knowledge, you can now unleash the full potential of TextView in your Android applications.

Implementing a simple Container with Text in Flutter

In Flutter, the Container widget is a useful and frequently used widget. It can be tailored to create more intricate layouts with borders, shadows, and other decorations, or it can be used to build straightforward boxes to hold other widgets.

The Container widget’s primary function is to give padding and margin around other widgets. You may create spacing around the content of the container using the padding and margin properties, which is helpful for designing more aesthetically pleasing layouts.

The Container widget also lets you alter the box’s decoration in addition to padding and margin. The decorating property, which accepts a BoxDecoration object, is used for this.

Container(
  width: 200.0,
  height: 100.0,
  margin: EdgeInsets.all(16.0),
  padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(8.0),
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        spreadRadius: 2,
        blurRadius: 5,
        offset: Offset(0, 3),
      ),
    ],
  ),
  child: Text(
    'This is a Container widget!',
    style: TextStyle(fontSize: 16.0),
  ),
)

With the help of the BoxDecoration class, you may alter the container’s appearance by changing things like the colour, border radius, and box shadow. Even with just the Container widget and some simple styling, you can come up with some truly intriguing and inventive layouts.

We construct a Container widget with a white backdrop, rounded corners, and a box shadow using the example code shown above. In order to display some text, we also add some padding and margin to the container and a Text widget as a child of the container.

Overall, the Flutter Container widget is a strong and adaptable tool for building unique layouts. The Container widget is a fantastic tool for creating more complicated aesthetic elements or adding space around other widgets.