Home Blog

How to create Flutter SelectableText Widget

0
How to create selectable text in flutter
flutter selectable text

Hi Guys, Welcome to Proto Coders Point, In this flutter Article will learn how to implement a Text Widget that can be selectable,.So to acheive this will make use of flutter selectableText widget, so that a app user can easily select the text, copy it & paste easily.

Usually when we develop any mobile application, The Text with-in the app cannot be selectable to copy(by default),Like how be can perform copy & post operation on website kinds of app.

In this Flutter tutorial lets learn how to make a text selectable in flutter using selectable text widget in flutter app.

Let’s get started

Flutter selectableText

Selectable Text has 2 types of constructor that you can use to give customized styling for TextWidget.

Flutter Single Style Selectable Text Widget (Contructor)

SelectableText(
   String data, 
   {
      Key? key, 
      FocusNode? focusNode, 
      TextStyle? style, 
      StrutStyle? strutStyle, 
      TextAlign? textAlign, 
      TextDirection? textDirection, 
      double? textScaleFactor, 
      bool showCursor = false, 
      bool autofocus = false, 
      ToolbarOptions? toolbarOptions, 
      int? minLines, 
      int? maxLines, 
      double cursorWidth = 2.0, 
      double? cursorHeight, 
      Radius? cursorRadius, 
      Color? cursorColor, 
      selectionHeightStyle = ui.BoxHeightStyle.tight, 
      BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,  
      DragStartBehavior dragStartBehavior = DragStartBehavior.start, 
      bool enableInteractiveSelection = true, 
      TextSelectionControls? selectionControls, 
      GestureTapCallback? onTap, 
      ScrollPhysics? scrollPhysics, 
      String? semanticsLabel, 
      TextHeightBehavior? textHeightBehavior, 
      TextWidthBasis? textWidthBasis, 
      SelectionChangedCallback? onSelectionChanged
    }
)

Multi-style Selectable Text (constructor)

SelectableText.rich(
   TextSpan textSpan, 
   {
     Key? key, 
     FocusNode? focusNode, 
     TextStyle? style, 
     StrutStyle? strutStyle, 
     TextAlign? textAlign, 
     TextDirection? textDirection, 
     double? textScaleFactor, 
     bool showCursor = false, 
     bool autofocus = false, 
     ToolbarOptions? toolbarOptions, 
     int? minLines, int? maxLines, 
     double cursorWidth = 2.0, 
     double? cursorHeight, 
     Radius? cursorRadius, 
     Color? cursorColor, 
     BoxHeightStyle selectionHeightStyle = ui.BoxHeightStyle.tight, 
     BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,  
     DragStartBehavior dragStartBehavior = DragStartBehavior.start, 
     bool enableInteractiveSelection = true, 
     TextSelectionControls? selectionControls, 
     GestureTapCallback? onTap, 
     ScrollPhysics? scrollPhysics, 
     String? semanticsLabel, 
     TextHeightBehavior? textHeightBehavior, 
     TextWidthBasis? textWidthBasis, 
     SelectionChangedCallback? onSelectionChanged
   }
)

Example on How to use Flutter Selectable Text Widget

In below Example, Will implement selectable text, where I will you how to use both SelectableText & SelectableText.rich constructor class, and in below code I have added a textfield so that user can select text and paste it in flutter textField.

import 'dart:ui';
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(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Selectable Text Example - ProtoCodersPoint.com')),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: const [
            Text("This is normal text widget, not selectable",style: TextStyle(fontSize: 30),),
            SizedBox(
              height: 20,
            ),
            // SelectableText
            SelectableText(
              'Long Press on me to Copy me, Try it now.',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 20,
            ),
            // SelectableText.rich example 
            SelectableText.rich(TextSpan(
                text: 'The computer was born to solve problems, ',
                style: TextStyle(fontSize: 20),
                children: [
                  TextSpan(
                      text: 'that did not exist before. – ',
                      style: TextStyle(color: Colors.blue)),
                  TextSpan(
                      text: 'Bill Gates',
                      style: TextStyle(color: Colors.red))
                ])),
            SizedBox(
              height: 20,
            ),
            TextField(
              minLines: 3,
              maxLines: 10,
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Paste Copyed Text Here to know is it actually worked'),
            ),
          ],
        ),
      ),
    );
  }
}

Android Studio Convert Java to Kotlin not working – 100% Solution

0
Android Studio Convert Java to Kotlin not working

Hi Guy’s Welcome to Proto Coders Point. In this android studio article will learn to how to convert java file to kotlin & some developer are facing some error while converting java to kotlin let’s fix it.

How to Convert Android jave code to kotlin

Time needed: 1 minute.

  1. Step 1

    Select the java file that you want to convert

  2. Step 2

    In Android Studio menubar goto Code

  3. Step 3

    In code menu you will see a option “convert java file to kotlin file”, Click on it and your file will get converted automatically to .kt.

    how to convert java file to kotlin in android studio


Android Studio Convert Java to Kotlin not working

I was just trying to convert my old android project which is in JAVA language to kotlin but encounter and error:

Build was configured to prefer settings repositories over project repositories but repository ‘MavenRepo’ was added by build file ‘app\build.gradle.

Then after lot’s of research and solution by developer on stackoverflow I finally found out the 100% working solution on Android Convert Java File to Kotlin Not working.


Solution

You need to update settings.gradle

Replace this line

repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)

with this

repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)

Refer below screenshot for easily understanding

Now hit on sync now, and try to convert file by following above steps.

Thanks Me, By Subscribing me on youtube ProtoCodersPoint.

Android Copy Text to Clipboard Programmatically – JAVA/KOTLIN

0
Android Copy Text to Clipboard Programmatically
copy to clipboard android

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial will learn how to copy a text programmatically into clipboard in android apps, Source Code below for both JAVA & KOTLIN developer.

Copy text to clipboard android programmatically

Below is complete source code to learn how to copy and paste on android programmatically (copy to clipboard android).

To Implement the same, we will use android clipboard manager

clipboard manager in android

Basically, android clipboard manager is a interface to a clipboard services, use to easily save any text in clipData and to retrieve the text global in a mobile device.

The ClipboardManager is best, easily to use & understand: it contains some methods by which we can get & set the current clipboard data as primary copyed text.

Snippet Code For Java

  ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

  ClipData clipData = ClipData.newPlainText("label","The Text you want to copy in clipboard");  // Example: In real-time, Value from textview

  clipboardManager.setPrimaryClip(clipData);

Snippet Code For Kotlin

  val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager

  val clipData = ClipData.newPlainText("label", txtview2cpy!!.text.toString())

  clipboardManager.setPrimaryClip(clipData)

Clipboard manager android example with source code

Note: Below code is just an example, Use it to implement in real-time projects. ALL THE BEST.

Code Explaination in brief

Below I have 2 views (TextView & a Button). In TextView I have a text that I want to copy into android clipboard as PainText data, Then I have a button that simply copy the text from textview and get saved into clipdata (so that I can paste the copied text somewhere else easily).

activity_main.xml – UI Design

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtview2cpy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textAlignment="center"
        android:text="On Click, This TextView Text get Copyed in clipboard programmatically...!!"
        android:textSize="22dp"
        app:layout_constraintBottom_toTopOf="@+id/bCopyText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/bCopyText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copy"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt – For Kotlin Developer

package example.on.androidtextcopy

import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import android.os.Bundle
import example.on.androidtextcopy.R
import android.content.ClipData
import android.content.ClipboardManager
import android.view.View
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    var txtview2cpy: TextView? = null
    var bCopyText: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        txtview2cpy = findViewById<View>(R.id.txtview2cpy) as TextView
        bCopyText = findViewById<View>(R.id.bCopyText) as Button
        val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        bCopyText!!.setOnClickListener {
            val clipData = ClipData.newPlainText("label", txtview2cpy!!.text.toString())
            clipboardManager.setPrimaryClip(clipData)
            Toast.makeText(this@MainActivity, "Text Copyed", Toast.LENGTH_SHORT).show()
        }
    }
}

MainActivity.javacopy to clipboard android programmatically

package example.on.androidtextcopy;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView txtview2cpy;
    Button bCopyText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtview2cpy = (TextView) findViewById(R.id.txtview2cpy);
        bCopyText = (Button) findViewById(R.id.bCopyText);
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        bCopyText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipData clipData = ClipData.newPlainText("label",txtview2cpy.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this,"Text Copyed",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

How to Check if string is empty/Null in flutter

0
how to Check if string is empty in dart
how to Check if string is empty in dart

Hi Guy’s Welcome to Proto Coders Point, In this Flutter dart article let’s learn how to validate a String Variable to check if the given String is empty or null.

Suppose, You are building an application where you ask user to enter some data & you don’t accept empty or null value.

At situation, we need to check if string is empty or null, Let’s Start:

Function to check of String is null or empty

Will create a function/method that will validate our string, Let’s name the function as stringValidator()

bool stringvalidator(String? value) {
  if (value == null) {
    return false;
  }

  if (value.isEmpty) {
    return false;
  }

  return true;
}

Let’s make the above function shorter by using ternary operation in dart.

bool stringvalidator(String? value) {
   return value?.isNotEmpty ?? false;
}

The above function, return true if String variable contain atleast one character, else return false if string is empty or null.

Complete Code – To check if string variable is empty or null in dart Flutter

bool stringvalidator(String? value) {
   return value?.isNotEmpty ?? false;
}

void main() {
  print(stringvalidator(''));   // false
  print(stringvalidator('Rajat Palankar'));    // true
  print(stringvalidator(null));   // false
}

Listview Selected Item Next Page with Next and Previous Button

0
flutter listview pass data
flutter listview pass data

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial article will learn how to build listview with list of items in it, & onTap selected item will be displayed on next screen, In the mean while will learn how to pass selected data to next screen.

I has already wrote a complete article on “Flutter Listview onTap Selected Item – send data to new screen” and have a complete step by step video tutorial on youtube ( Check below Video at bottom on this article ).

Flutter Listview OnTap Pass Selected Data to Next Page, with Next & Previous Button to switch items

Video Tutorial


Flutter Listview onTap pass data to next page & has next & previous button on page 2

So when user select an item from listview.builder, the selected item data is been passed to page 2 and data is been shown, but if the user wants to read next data item from the list then he has to go back to first page and select the next data item from listview, which is not fully userfriendly.

In this flutter tutorial article, will add new Feature i.e:

In page no 2, There will be 2 buttons (previous & next) by using which user can change or swap the item from listview by being in page 2 itself. There is not need for user to go back to page 1 to select next item from list.


Complete Source Code – Flutter Listview With Example

Step by Step

We need to create 2 Screen and a dataModel class

(Screen 1) main.dart: Will generate list of data and show in flutter listview.

(Screen 2) FruitDetail.dart: User selected item data will be shown here.

(DataModel) FruitDataModel: Holds Information or a data.

Create above 3 files, for better understanding refer my file project structure.

1. FruitDataModel.dart

A Data Model are class of entities that holds information or a data.

In our app, DataModel has 3 String datatype.

Eg: Name of Fruit.
ImageUrl of Fruit.
Description of Fruit.

Code DataModel

class FruitDataModel{
  final String name,ImageUrl,desc;

  FruitDataModel(this.name, this.ImageUrl, this.desc);
}

DataModel will have a constructor to assign the value to variables strings.


2. FruitDetail.dart

In fruitDetail page, will display details of selected Item from the listview of flutter app.

FruitDetail has a constructor that accept 2 parameter from page 1(main.dart) while navigating.

  1. Index of user selected item from list.
  2. FruitDataModel The whole List of data.

It also has 2 buttons (Prev & Next) by which user can change contents of the page.

Code – FruitDetial.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:listview_on_tap/FruitDataModel.dart';
import 'dart:convert';

class FruitDetail extends StatefulWidget {
  final List<FruitDataModel> fruitDataModel;
  int index;
  FruitDetail({Key? key, required this.index, required this.fruitDataModel}) : super(key: key);

  @override
  State<FruitDetail> createState() => _FruitDetailState();
}

class _FruitDetailState extends State<FruitDetail> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.fruitDataModel[widget.index].name),),
      body: Column(
        children: [
          Image.network(widget.fruitDataModel[widget.index].ImageUrl),
          SizedBox(
            height: 10,
          ),
          Text(widget.fruitDataModel[widget.index].desc,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 20),),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              FloatingActionButton(
                heroTag: "f1",
                onPressed: (){
                  setState(() {
                    if(widget.index!=0){
                      widget.index --;
                    }
                  });
                },
                child:Icon(Icons.arrow_back_ios) ,
              ),
              FloatingActionButton(
                heroTag: "f2",
                onPressed: (){
                  setState(() {
                    if(widget.index != widget.fruitDataModel.length-1){
                      widget.index ++;
                    }
                  });
                },
                child:Icon(Icons.arrow_forward_ios),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

3. main.dart

main.dart is the first page/screen, Here we will generate list of data and then pass the list to show the data in listview.builder.

Then when user onTap on any item from listview, we are using Navigator to navigate the user from main.dart to fruitDetail.dart page.

With PageNavigator we are passing 2 parameter to page 2 (fruitDetail.dart)

  • Index of user selected item from list.
  • FruitDataModel The whole List of data.

Code main.dart

import 'package:flutter/material.dart';
import 'package:listview_on_tap/FruitDataModel.dart';
import 'package:listview_on_tap/FruitDetail.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  static List<String> fruitname =['Apple','Banana','Mango','Orange','pineapple'];

  static List<String> url = ['https://www.applesfromny.com/wp-content/uploads/2020/05/Jonagold_NYAS-Apples2.png',
    'https://cdn.mos.cms.futurecdn.net/42E9as7NaTaAi4A6JcuFwG-1200-80.jpg',
    'https://upload.wikimedia.org/wikipedia/commons/thumb/9/90/Hapus_Mango.jpg/220px-Hapus_Mango.jpg',
    'https://5.imimg.com/data5/VN/YP/MY-33296037/orange-600x600-500x500.jpg',
    'https://5.imimg.com/data5/GJ/MD/MY-35442270/fresh-pineapple-500x500.jpg'];

  final List<FruitDataModel> Fruitdata = List.generate(fruitname.length, (index) => FruitDataModel('${fruitname[index]}', '${url[index]}','${fruitname[index]} Description...'));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Pass Data from ListView to next Screen'),),
        body: ListView.builder(
            itemCount: Fruitdata.length,
            itemBuilder: (context,index){
              return Card(
                child: ListTile(
                  title: Text(Fruitdata[index].name),
                  leading: SizedBox(
                    width: 50,
                    height: 50,
                    child: Image.network(Fruitdata[index].ImageUrl),
                  ),
                  onTap: (){
                    Navigator.of(context).push(MaterialPageRoute(builder: (context)=>FruitDetail(index: index,fruitDataModel: Fruitdata,)));
                  },
                ),
              );
            }
        )
    );
  }
}

The Below Video is only to learn how to pass data selected from listview item to next page.

Multiple heroes that share the same tag within a subtree – FloatingActionButton

0

Hi Guys Welcome to Proto Coders Point. This article is on a quick solution to an error i.e "There are multiple heroes that share the same tag within a subtree" in flutter.

Long time ago while developing a flutter application for my client, I encountered an error been show when I used 2 or more FloatingActionButton on same page.

How to Solve Multiple Heroes error in flutter

My FloatingActionButton Previous Snippet Code

floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FloatingActionButton(
            onPressed: (){},
            child:Icon(Icons.arrow_back_ios) ,
          ),
          FloatingActionButton(onPressed: (){},
            child:Icon(Icons.arrow_forward_ios),
          ),
        ],
      ),
I/flutter (21786): In this case, multiple heroes had the following tag: default FloatingActionButton tag

Here the Error simple means that, If you are adding more then 1 FloatingActionButton widget in one page or screen, then you have to add heroTag to each FloatingActionButton widget.

My FloatingActionButton after adding heroTag

floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FloatingActionButton(
            heroTag: "f1",   // add a unique tag
            onPressed: (){},
            child:Icon(Icons.arrow_back_ios) ,
          ),
          FloatingActionButton(
            heroTag: "f2",   // add a unique tag
            onPressed: (){},
            child:Icon(Icons.arrow_forward_ios),
          ),

        ],
      ),

Just by adding unique heroTag to FloatingActionButton the error will get solved 100%.