Author

admin

Browsing

2 Flutter Folder Picker Examples with Tutorial

Hi, Welcome to AndroidRide.

Sometimes, users need to pick directories to store their data or download files. In this post, you will learn how to pick directories using two flutter packages.

okay..Let’s start then.

Let’s create a Flutter project – Check this tutorial, if you are a beginner.

How To Pick Folder Using easy_folder_picker package – Only Android.

flutter folder picker using easy_folder_picker

You can also use Flutter command to create project.

I am using Flutter 2.5.1
Dart: 2.12.0

You need to import the dependency in pubspec.yaml file.


  easy_folder_picker: ^1.1.1

flutter folderpicker permissions

Also, import these permissions in android/app/src/main/AndroidManifest.xml.


<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

//if you want to create folders by users

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

//In Android Q
<application
      android:requestLegacyExternalStorage="true"

Now this package only supports Android. It handles requesting permissions as well. Next you need to set compileSdkVersion to 31 in android/app/build.gradle


android {
  compileSdkVersion 31

  • FolderPicker.ROOTPATH: “/storage/emulated/0/”
  • When the ElevatedButton taps it calls _selectDirectory().
  • FolderPicker.pick() return which directory you have selected.
  • Using setState method, we will rebuild the UI.

 Directory? selectedDirectory;

  void _selectDirectory(BuildContext context) async {
    Directory? directory = selectedDirectory;
    directory ??= Directory(FolderPicker.ROOTPATH);

      Directory? newDirectory = await FolderPicker.pick(
      allowFolderCreation: true,
      context: context,
      rootDirectory: directory,
    );

    setState(() {
      selectedDirectory = newDirectory;
      //print(selectedDirectory);
    });
  }


Here we go, the complete code is here.

Complete Source Code


import 'dart:io';
import 'package:easy_folder_picker/FolderPicker.dart';
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Folder Picker',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const FolderPickerScreen(),
    );
  }
}

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

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

class _FolderPickerScreenState extends State<FolderPickerScreen> 
{
  Directory? selectedDirectory;

  void _selectDirectory(BuildContext context) async {
    Directory? directory = selectedDirectory;
    directory ??= Directory(FolderPicker.ROOTPATH);
      Directory? newDirectory = await FolderPicker.pick(
      allowFolderCreation: true,
      context: context,
      rootDirectory: directory,
    );

    setState(() {
      selectedDirectory = newDirectory;
      //print(selectedDirectory);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Folder Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                _selectDirectory(context);
              },
              child: const Text('Select Directory'),
            ),
            const SizedBox(
              height: 10,
            ),
            selectedDirectory == null
                ? const Text('No directory selected')
                : Text("Directory Path: ${selectedDirectory!.path}")
          ],
        ),
      ),
    );
  }
}


Flutter folder Picker Using filesystem_picker package

folder picker filesystem_picker package
In this example, we will use filesystem_picker package.
You need to add below dependencies in pubspec.yaml file.


filesystem_picker: ^2.0.0
permission_handler: ^8.2.5

Also, import these permissions in android/app/src/main/AndroidManifest.xml.


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

  • _prepareStorage() method initialize the rootPath to ‘/storage/emulated/0/’.
  • FilesystemPicker.open() return path of the selected directory.
  • Rebuilds UI using setState method.

Future<void> _prepareStorage() async 
  {
    rootPath = Directory('/storage/emulated/0/');
    setState(() {});
  }

  Future<void> _pickDir(BuildContext context) async 
  {
  
    String? path = await FilesystemPicker.open(
      title: 'Select folder',
      context: context,
      rootDirectory: rootPath!,
      fsType: FilesystemType.folder,
      pickText: 'Select this folder',
      folderIconColor: Colors.teal,
      requestPermission: () async =>
          await Permission.storage.request().isGranted,
    );

    setState(() {
      dirPath = path;
    });
  }


Full Source Code


import 'dart:io';
import 'package:filesystem_picker/filesystem_picker.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() 
{
  runApp(
    const MaterialApp(
      home: MyApp(),
    ),
  );
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Directory? rootPath;
  String? dirPath;

  @override
  void initState() {
    super.initState();
    _prepareStorage();
  }

  Future<void> _prepareStorage() async 
  {
    rootPath = Directory('/storage/emulated/0/');
    setState(() {});
  }

  Future<void> _pickDir(BuildContext context) async 
  {
  
    String? path = await FilesystemPicker.open(
      title: 'Select folder',
      context: context,
      rootDirectory: rootPath!,
      fsType: FilesystemType.folder,
      pickText: 'Select this folder',
      folderIconColor: Colors.teal,
      requestPermission: () async =>
          await Permission.storage.request().isGranted,
    );

    setState(() {
      dirPath = path;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Directory Picker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            dirPath != null
                ? Padding(
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    child: Text('$dirPath'),
                  )
                : const Padding(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Text('No directory selected'),
                  ),
            ElevatedButton(
              child: const Text('Select directory'),
              onPressed: (rootPath != null) ? () => _pickDir(context) : null,
            ),
          ],
        ),
      ),
    );
  }
}


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

Flutter Animated Icon Example With Tutorial

Hi, Welcome to AndroidRide.

Animation always helps our app to stand out from other apps. In Flutter, By default there are lots of Animated Widgets. So in this post, you will learn about Flutter Animated Icon widget.

okay… How it works?
flutter animated icon example
It gets changed into one icon to another with animation.

How To Use AnimatedIcon In Flutter project?


AnimatedIcon(
            icon: AnimatedIcons.pause_play,
            progress: _animationController,
          )

AnimatedIcon needs 2 things.

  1. AnimatedIconData icon: Icon you want to show.
  2. Animation progress: Animation for the icon.

AnimatedIcon Example In Simple Steps

Let’s start doing… Before that, What we will do next in simple steps?

  1. Create a Stateful widget.
  2. Extend the class with SingleTickerProviderStateMixin using with keyword.
  3. Create an AnimationController.
  4. Initialize the AnimationController inside initState.
  5. Use the AnimationController instance as progress value of AnimatedIcon.
  6. Control the animation through tap events.
  7. Dispose the AnimationController inside dispose() method.

Flutter AnimatedIcon Example

Create a Flutter project – check this tutorial.

If you are using Visual Studio – you can create a project using CTRL + SHIFT + P(windows).

I assume you have created a project, So clear the main.dart file.

  • Create a stateful widget by typing stful and also add main() method.
  • Or Just copy the below code.

import 'package:flutter/material.dart';

void main() => const AnimatedIconExample();

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

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

class _AnimatedIconExampleState extends State<AnimatedIconExample> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


Next we need to create an AnimationController.

  • As a first step, lets extend a Mixin called SingleTickerProviderStateMixin. We are creating only one AnimationController, that’s why SingleTickerProviderStateMixin is used.
  • If you have multiple AnimationController, use TickerProviderStateMixin.
  • Create an AnimationController object and initialize it in initState.


class _AnimatedIconExampleState extends State<AnimatedIconExample>
    with SingleTickerProviderStateMixin {
  
  late AnimationController _animationController;


  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
  }
  • GestureDetector used for detecting tap events.
  • Here 200 used for AnimatedIcon size, and green as color.
  • AnimationController vsync property needs Ticker, that’s the reason we need to extend SingleTickerProviderStateMixin with our class.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: GestureDetector(
          onTap: () {
           // changeIcon();
          },
          child: AnimatedIcon(
            size: 200,
            color: Colors.green,
            icon: AnimatedIcons.pause_play,
            progress: _animationController,
          ),
        ),
      ),
    );
  }


Let’s create a variable for changing animation state.

  • Based on isAnimating value, icon changes one to another.
  • forward() method starts running the animation forwards to end.
  • reverse() method starts running the animation in reverse to beginning.

bool isAnimating = false;

void changeIcon() {
    setState(() {
      isAnimating = !isAnimating;

      isAnimating
          ? _animationController.forward()
          : _animationController.reverse();
    });
  }

  • Finally, Just like TextEditingController, Animationcontroller also need to dispose in dispose method.

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

Check out the complete source code.


import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      home: AnimatedIconExample(),
    ),
  );
}

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

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

class _AnimatedIconExampleState extends State<AnimatedIconExample>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  bool isAnimating = false;

  @override
  void initState() {
    super.initState();
//
    _animationController = AnimationController(
      vsync: this,//vsync needs Ticker
      duration: const Duration(seconds: 1),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: GestureDetector(
          onTap: () {
//tap event calls the method, and start animating icon.
            changeIcon();
          },

          child: AnimatedIcon(
            size: 200,//size of the AnimatedIcon
            color: Colors.green,//color of the AnimatedIcon
            icon: AnimatedIcons.pause_play,
            progress: _animationController,
          ),
        ),
      ),
    );
  }

  void changeIcon() {
//rebuilds UI with changing icon.
    setState(() {
      isAnimating = !isAnimating;

      isAnimating
          ? _animationController.forward()
          : _animationController.reverse();
    });
  }
//disposes AnimationController.
  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
}



flutter animated icon example

Flutter AnimatedIcon List

Let’s check out the icons you can use now.

  • add_event
  • arrow_menu
  • close_menu
  • ellipsis_search
  • event_add
  • home_menu
  • list_view
  • menu_arrow
  • menu_close
  • menu_home
  • pause_play
  • play_pause
  • search_ellipsis
  • view_list

AnimatedIcon Properties

Color? color: Color used to paint the icon.
AnimatedIconData icon: The animated icon you need to show.
Animation progress: Animation progress for the AnimatedIcon.
double? size: Size of the AnimatedIcon widget.
TextDirection? textDirection: The text direction used for rendering the icon.
String? semanticLabel: Available in accessibility modes (TalkBack). It doesn’t shown in the UI.

Download Source Code

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

5 Flutter Bottom Button Examples With Tutorial

Hi guys, Welcome to AndroidRide.

Most of the apps are using bottom button for implementing their app’s main functionality. For creating todos, notes etc. So if you are trying to implement something like that, then you are in the right place.

okay… Let’s start.

1. Flutter Bottom Button Using FloatingActionButton

Let’s start with FloatingActionButton.

bottom button fab

You can align FloatingActionButton position to center or almost anywhere using Scaffold‘s floatingActionButtonLocation property.

  • Use FloatingActionButtonLocation.centerFloat to make FAB to align to bottom.
  • I am already talked about this in FloatingActionButton tutorial.

floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: const Icon(
          Icons.edit,
          color: Colors.white,
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,

2. Bottom Button Using FloatingActionButton.extended()

In this example, we will use FloatingActionButton.extended constructor and will make a button at the bottom. Location remains same like in the first example.

Yes, FloatingActionButtonLocation.centerFloat


floatingActionButton: FloatingActionButton.extended(
        onPressed: () {},
        icon: const Icon(Icons.edit),
        label: const Text('Edit'),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,

3. Flutter Bottom Button Using BottomNavigationBar

flutter bottom button

Bottom Navigation Bar can be used to set Navigation Icons. But here, we will use it to implement a button. I didn’t use button widget here.

  • kToolbarHeight used to set button’s height. It’s actually 56.0.

 bottomNavigationBar: Material(
        color: const Color(0xffff8906),
        child: InkWell(
          onTap: () {
            //print('called on tap');
          },
          child: const SizedBox(
            height: kToolbarHeight,
            width: double.infinity,
            child: Center(
              child: Text(
                'Bottom Button',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
      ),


4. Bottom Button Using BottomNavigationBar – Two Items

flutter bottom button using bottomnavigationbar

In this example, just like above one. But we will add two buttons here.

  • InkWell used for ripple effect.
  • Recommended to use SizedBox, If you do not have any other properties except width, height and child.

bottomNavigationBar: Row(
        children: [
          Material(
            color: const Color(0xffff8989),
            child: InkWell(
              onTap: () {
                //print('called on tap');
              },
              child: const SizedBox(
                height: kToolbarHeight,
                width: 100,
                child: Center(
                  child: Text(
                    'Click',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: Material(
              color: const Color(0xffff8906),
              child: InkWell(
                onTap: () {
                  //print('called on tap');
                },
                child: const SizedBox(
                  height: kToolbarHeight,
                  width: double.infinity,
                  child: Center(
                    child: Text(
                      'Bottom Button',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),

5. Bottom Button Using Stack and Align

flutter bottom button

In this example, we will use Stack for containing children widgets and Align for aligning button to the bottom. RaisedButton is deprecated, so here we used ElevatedButton.

  • Stack widget contains ListView, Align.
  • Inside ListView, There are 3 Text items.
  • ElevatedButton width is maximum, but container margin creates empty space around it. Just like Padding widget.

body: Stack(
        children: [
          ListView(
            children: const [
              Text('Item 1'),
              Text('Item 2'),
              Text('Item 3'),
            ],
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              margin: const EdgeInsets.all(5),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {},
                child: const Text('Bottom Button '),
              ),
            ),
          )
        ],
      ),

Download Source Code

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

2 Ways To Make Clickable Container in Flutter: 3 Examples

Do you want to make a clickable container in Flutter?

Then this post is definitely for you.

By default, Container doesn’t have any onPress or onTap property. So we need to use any of the widgets given below.

  1. GestureDetector.
  2. InkWell – it has ripple effect.

Let’s start with GestureDetector.

1. How To Make A Clickable Container Using GestureDetector?

clickable container using gesturedetector in flutterGestureDetector widgets used to detect gestures, so it provides number of sensing properties. But here we will use the onTap property.

Using GestureDetector, you don’t need to code a lot. Just wrap your container with GestureDetector.
gesturedetector container

  • If you are using Visual Studio, Click on the Container widget and click on the yellow bulb icon or use Ctrl + Dot key (keyboard shortcut – Windows). Then it displays the context menu.
  • Select wrap with widget and change widget to GestureDetector.
  • Provide onTap property and anonymous function as it’s value.
  • You can also give function name, I just mention anonymous function for this example.
  • That’s all.
    • When container tapped, onTap calls and prints the content.
    GestureDetector(
              onTap: () {
                print('GestureDetector onTap Called');
              },
              child: Container(
                child: Center(
                  child: Text(
                    'Clickable Container Using GestureDetector',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
    

    2. How To Make Clickable Container Using InkWell?

    clickable container using inkwell

    Like GestureDetector, You can use InkWell widget to make Container clickable and it also provides ripple effect.

    • Wrap the container with Inkwell and create onTap property.

    that’s it. everything done.

    InkWell(
              onTap: () {
                print('InkWell onTap Called');
              },
              child: Container(
                child: Center(
                  child: Text(
                    'Clickable Container Using InkWell',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
    

    3. Create a Clickable AnimatedContainer

    clickable animated container

    In this example, we will use AnimatedContainer – Animated version of Container. Let’s animate container height when a tap occurs.

    • if _initialValue is true, then AnimatedContainer width and height set to 200.
    • When _initialValue becomes false, height and width becomes 300.
    • When the user taps, setState() rebuilds the UI with _initialValue.
      bool _initialValue = true;
    ....
    ..
    .
    GestureDetector(
                onTap: () {
                  setState(() {
                    _initialValue = !_initialValue;
                  });
                },
                child: AnimatedContainer(
                  duration: const Duration(seconds: 2),
                  color: Colors.amber,
                  height: _initialValue ? 200 : 300,
                  width: _initialValue ? 200 : 300,
                  child: Center(
                    child: const Text(
                      'Clickable AnimatedContainer Using GestureDetector',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
    
    

    Create a project with all the above examples.

    clickable container flutter

    • In this example, Column widget used to align each widgets vertically.
    • SizedBox used to give empty space between the widgets. You can also use Padding widget.
    • MainAxisAlignment.center makes the elements move to center.
    • Remove Debug Banner In Flutter
    
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> 
    {
    
      bool _initialValue = true;
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Clickable Container In Flutter',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              title: Text('Clickable Container In Flutter'),
            ),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  height: 20,
                ),
                GestureDetector(
                  onTap: () {
                    print('GestureDetector onTap Called');
                  },
                  child: Container(
                    child: Center(
                      child: Text(
                        'Clickable Container Using GestureDetector',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                InkWell(
                  onTap: () {
                    print('InkWell onTap Called');
                  },
                  child: Container(
                    child: Center(
                      child: Text(
                        'Clickable Container Using InkWell',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                InkWell(
                  onTap: () {
                    setState(() {
                      _initialValue = !_initialValue;
                    });
                  },
                  child: AnimatedContainer(
                    duration: const Duration(seconds: 2),
                    color: Colors.amber,
                    height: _initialValue ? 200 : 300,
                    width: _initialValue ? 200 : 300,
                    child: Center(
                      child: Text(
                        'Clickable AnimatedContainer Using GestureDetector',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    
    

    Run the application.

    Download Source Code

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

4 Flutter ListView Navigation Examples With Tutorial

List Applications are everywhere. Social Media Apps, Note Taking Apps. Yes, the list won’t end.

So if you are trying to make a List App and want to navigate to a new screen when the user taps.

This post will definitely good for you.

1. ListView Navigation: Navigate To New Screen.

flutter listview navigation

In this simple example, you will learn how to navigate to a different screen through ListTile onTap function.

  • I have used 3 ListTiles. When the user taps a ListTile, it calls onTap Function.
  • Then Navigator pushes the screen.

Below is the code.

ListTile(
            title: Text('First Screen'),
            trailing: Icon(Icons.keyboard_arrow_right_sharp),
//onTap calls When ListTile Taps
            onTap: () {
//Navigator pushes FirstScreen.
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => FirstScreen(),
                ),
              );
            },
          ),

Full source code is given below.


import 'package:flutter/material.dart';
import 'first_screen.dart';
import 'second_screen.dart';
import 'third_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ListView Navigation I',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyListView(),
    );
  }
}

class MyListView extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter ListView Navigation I'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: Text('First Screen'),
            trailing: Icon(Icons.keyboard_arrow_right_sharp),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => FirstScreen(),
                ),
              );
            },
          ),
          ListTile(
            title: Text('Second Screen'),
            trailing: Icon(Icons.keyboard_arrow_right_sharp),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => SecondScreen(),
                ),
              );
            },
          ),
          ListTile(
            title: Text('Third Screen'),
            trailing: Icon(Icons.keyboard_arrow_right_sharp),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ThirdScreen(),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}


Next, You have to make 3 Screens. FirstScreen, SecondScreen and ThirdScreen. What you want to do is copy the below code of FirstScreen and make three screen dart files.

Replace FirstScreen text whereever you see in SecondScreen and ThirdScreen.

You can also download the source code at the bottom.

first_screen.dart


import 'package:flutter/material.dart';

class FirstScreen extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 150.0, vertical: 10),
        child: Text(
          'First Screen',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

2. Flutter ListView Navigation + Passing Data

listview navigation with passing data
In this example, while navigating to DetailScreen, we also pass data. How will we do that?

  • In this example, when the tap occurs, we use index of ListView and take Note data from _noteList and pass it to DetailScreen constructor.
  • DetailScreen(note: _noteList[index]) :
  • //_noteList store Note Items.
    final List<Note> _noteList = [
        Note(
          title: 'Note Title 1',
          content: 'Note Content 1',
        ),
        Note(
          title: 'Note Title 2',
          content: 'Note Content 2',
        ),
        Note(
          title: 'Note Title 3',
          content: 'Note Content 3',
        )
      ];
    ...
    ..
    .
    ListView.builder(
              itemCount: _noteList.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(
                    _noteList[index].title,
                  ),
                  subtitle: Text(
                    _noteList[index].content,
                  ),
                  onTap: () {
    //Navigator pushes the DetailScreen and Passes the note data through constructor.
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => DetailScreen(note: _noteList[index]),
                      ),
                    );
                  },
                );
              }),
    
    
  • How to receive this data in DetailScreen?
  • 
    class DetailScreen extends StatelessWidget {
      final Note note;
      const DetailScreen({required this.note});
    
    
    

Let’s create the complete project… So make 3 dart Files.

  1. note.dart
  2. main.dart
  3. detail_screen.dart

note.dart


class Note {
  final String title;
  final String content;

  Note({required this.title, required this.content});
}


main.dart


import 'package:flutter/material.dart';
import 'detail_screen.dart';
import 'note.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ListView Navigation + Passing Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ListScreen(),
    );
  }
}

class ListScreen extends StatelessWidget 
{

 final List<Note> _noteList = [
    Note(
      title: 'Note Title 1',
      content: 'Note Content 1',
    ),
    Note(
      title: 'Note Title 2',
      content: 'Note Content 2',
    ),
    Note(
      title: 'Note Title 3',
      content: 'Note Content 3',
    )
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView Navigation + Passing Data'),
      ),
      body: ListView.builder(
          itemCount: _noteList.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(
                _noteList[index].title,
              ),
              subtitle: Text(
                _noteList[index].content,
              ),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DetailScreen(note: _noteList[index]),
                  ),
                );
              },
            );
          }),
    );
  }
}


detail_screen.dart



import 'package:flutter/material.dart';

import 'note.dart';

class DetailScreen extends StatelessWidget {
  final Note note;
  const DetailScreen({required this.note});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Screen'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(

            children: [
              Text(
                note.title,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(note.content),
            ],
          ),
        ),
      ),
    );
  }
}


3.ListView Navigation – Passing Data Through RouteSettings

listview data passing routesettings
Just like constructor, you can also use RouteSettings to pass data. Just provide your data as value of arguments property.

 final List<Note> _noteList = [
    Note(
      title: 'Note Title 1',
      content: 'Note Content 1',
    ),
    Note(
      title: 'Note Title 2',
      content: 'Note Content 2',
    ),
    Note(
      title: 'Note Title 3',
      content: 'Note Content 3',
    )
  ];
.....
...
..
.
ListTile(
              title: Text(
                _noteList[index].title,
              ),
              subtitle: Text(
                _noteList[index].content,
              ),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DetailScreen(),
                    settings: RouteSettings(arguments: _noteList[index]),
                  ),
                );
              },
            )

Okay. How to get this data from DetailScreen?

  • Add below code inside build() method of DetailScreen.

final note = ModalRoute.of(context)!.settings.arguments as Note;


Exclamation mark – for null safety. If you are not using null safety, remove it.

note.dart


class Note {
  final String title;
  final String content;

  Note({required this.title, required this.content});
}


main.dart


import 'package:flutter/material.dart';

import 'detail_screen.dart';
import 'note.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter ListView Navigation - Passing Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ListScreen(),
    );
  }
}

class ListScreen extends StatelessWidget {
  ListScreen({Key? key}) : super(key: key);

  final List<Note> _noteList = [
    Note(
      title: 'Note Title 1',
      content: 'Note Content 1',
    ),
    Note(
      title: 'Note Title 2',
      content: 'Note Content 2',
    ),
    Note(
      title: 'Note Title 3',
      content: 'Note Content 3',
    )
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView - Passing Data(RouteSettings)'),
      ),
      body: ListView.builder(
          itemCount: _noteList.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(
                _noteList[index].title,
              ),
              subtitle: Text(
                _noteList[index].content,
              ),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DetailScreen(),
                    settings: RouteSettings(arguments: _noteList[index]),
                  ),
                );
              },
            );
          }),
    );
  }
}

detail_screen.dart


import 'package:flutter/material.dart';

import 'note.dart';

class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final note = ModalRoute.of(context)!.settings.arguments as Note;

    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Screen(RouteSettings)'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                note.title,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(note.content),
            ],
          ),
        ),
      ),
    );
  }
}



4.ListView Navigation To A Statefulwidget With Data + Hero Animation

listview navigation passing data to statefulwidget
In this example, When the ListTile tapped, will move to a DetailScreen which extends StatefulWidget and also displays simple Hero animation.

  • Hero tag value must be unique and you need to specify the same tag value in DetailScreen.
ListTile(
              leading: Hero(
//unique tag - image name
                tag: note.image,
                child: CircleAvatar(
                  backgroundImage: Image.asset('assets/${note.image}').image,
                ),
              ),
              title: Text(
                _noteList[index].title,
              ),
              subtitle: Text(
                _noteList[index].content,
              ),
              onTap: () {
//Navigator pushes the DetailScreen with note data.
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DetailScreen(_noteList[index]),
                  ),
                );
              },
            )

How to access this data in DetailScreen build method?

  • Inside build() method, you can use widget with field name.
  • Here, final note = widget.note.

class DetailScreen extends StatefulWidget {
  final Note note;

  DetailScreen(this.note);

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

class _DetailScreenState extends State<DetailScreen> {
  @override
  Widget build(BuildContext context) {
//widget.field name 
    final note = widget.note;


Let’s create the whole project. Source code of note.dart file is already given in above example.

Before that, you need to create assets directory to store image files. You can use your own image files or download our source code and use it . Also specify it in pubspec.yaml file.

main.dart


import 'package:flutter/material.dart';

import 'detail_screen.dart';
import 'note.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ListView Navigation - Passing Data With Hero Animation',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ListScreen(),
    );
  }
}

class ListScreen extends StatelessWidget {
  ListScreen({Key? key}) : super(key: key);

  final List<Note> _noteList = [
    Note(
      title: 'Note Title 1',
      content: 'Note Content 1',
      image: 'nature.jpg',
    ),
    Note(
      title: 'Note Title 2',
      content: 'Note Content 2',
      image: 'island.jpg',
    ),
    Note(
      title: 'Note Title 3',
      content: 'Note Content 3',
      image: 'stones.jpg',
    )
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView - Passing Data To Stateful Widget'),
      ),
      body: ListView.builder(
          itemCount: _noteList.length,
          itemBuilder: (context, index) {
            final note = _noteList[index];
            return ListTile(
              leading: Hero(
                tag: note.image,
                child: CircleAvatar(
                  backgroundImage: Image.asset('assets/${note.image}').image,
                ),
              ),
              title: Text(
                _noteList[index].title,
              ),
              subtitle: Text(
                _noteList[index].content,
              ),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DetailScreen(_noteList[index]),
                  ),
                );
              },
            );
          }),
    );
  }
}


detail_screen.dart


import 'package:flutter/material.dart';

import 'note.dart';

class DetailScreen extends StatefulWidget {
  final Note note;

  DetailScreen(this.note);

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

class _DetailScreenState extends State<DetailScreen> {
  @override
  Widget build(BuildContext context) {
    final note = widget.note;

    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Screen(RouteSettings)'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Hero(
                tag: note.image,
                child: Image.asset('assets/${note.image}'),
              ),
              SizedBox(height: 8),
              Text(
                note.title,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(note.content),
            ],
          ),
        ),
      ),
    );
  }
}


Download Source Code

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

Flutter TextField Password : 2 Examples

In this post, you will learn how to make a Password TextField. It’s really simple. So we will cover TextFormField too.

okay… Let’s start.

How To Make A Password Field In Flutter Using TextField?

TextField and TextFormField both have a property called obscureText. This property helps to show asterick sign while we typing on TextField. By default obscureText value is false. You need to change it to true then only it will show “*“.

For example, the code will be like below.
TextField(obscureText: true)

Let’s create a simple example.

Flutter TextField & TextFormField – Password Field Example

flutter textfield password
In this example, decoration is used to show the labelText. You don’t need to use it for making a password TextField.
You can comment decoration property if you want.

  TextField(
                  obscureText: true,
                  decoration: InputDecoration(labelText: 'TextField'),
                ),
                TextFormField(
                  obscureText: true,
                  decoration: InputDecoration(labelText: 'TextFormField'),
                ),

Full source code is given below.



import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter TextField & TextFormField Password Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter TextField & TextFormField Password Example'),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                TextField(
                  obscureText: true,
                  decoration: InputDecoration(labelText: 'TextField'),
                ),
                TextFormField(
                  obscureText: true,
                  decoration: InputDecoration(labelText: 'TextFormField'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }



How To Show/Hide Password With Visibility Icon

Let’s create a simple UI with hide/show password feature. Create a Flutter project in Android Studio. If you are using visual Studio, Ctrl + Shift + P and create New Flutter Project.

flutter textfield password icon animation

  • For showing a Lock icon inside TextField, you can use prefixIcon property of InputDecoration.
  • Use suffixIcon to show visibility/eye icon.
  • Use OutlineInputBorder for making rounded corners of TextField with BorderRadius.
  • textAlign: TextAlign.left: It aligns the text to left side.
  • When the visibility icon is tapped, it changes the value of hidePassword. Based on that obscureText value also changes.
  • SizedBox makes an empty space between TextField and Text.

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool hidePassword = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter TextField Password Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter TextField Password Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Type your password below...',
                  style: TextStyle(fontSize: 15), textAlign: TextAlign.left),
              SizedBox(
                height: 8,
              ),
              TextField(
                onChanged: (value) {
                  print(value);
                },
                obscureText: hidePassword,//show/hide password
                decoration: InputDecoration(
                  prefixIcon: Icon(Icons.lock),
                  suffixIcon: IconButton(
                    icon: hidePassword
                        ? Icon(Icons.visibility_off)
                        : Icon(Icons.visibility),
                    onPressed: () {
                      setState(() {
                        hidePassword = !hidePassword;
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),//circular border for TextField.
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


flutter textfield password with eye icon

Flutter Login Page (Other Post)

flutter login page with validation background image
Actually, this login page is from this post. If you are trying to make a login form with validation. It’s recommended to use Form and TextFormField. Using both you can create a better login form. You will also learn how to validate username and password.

So just check it out.

If you like this post, please share it with your family and friends.
Sharing is Caring…

Stadium Border in Flutter : 4 Examples

In this post, you will learn how to make stadium border-shaped widgets in Flutter. Rounded or stadium border type shape will look fresh and different when compared to rectangle-shaped widgets.

So here, you will see enough examples to learn and will get the confidence to make your own one.

What is Stadium Border in Flutter?

stadium border flutter
A border that looks like a stadium-shaped (a rectangle box with semicircles at the ends). StadiumBorder is frequently used with ShapeDecoration to create borders.

Let’s make one…

StadiumBorder Shape Using Container


Container has decoration property. So use this property with ShapeDecoration and make StadiumBorder shape.

          Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 10,
                ),
                decoration: ShapeDecoration(
                  color: Colors.red,
                  shape: StadiumBorder(),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),

stadium border in flutter using container
Let’s add a small border to the container. In this example, I have added white color to the border.


 Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 10,
                ),
                decoration: ShapeDecoration(
                  color: Colors.red,
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 2,
                      color: Colors.white,
                    ),
                  ),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),


Let’s make the border a little bit big, add more width inside BorderSide.

              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 10,
                ),
                decoration: ShapeDecoration(
                  color: Colors.red,
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 6,
                      color: Colors.green[200]!,
                    ),
                  ),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),

StadiumBorder using Container – II

stadium border container outline


   Container(
                padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                decoration: ShapeDecoration(
                  shape: StadiumBorder(
                    side: BorderSide(width: 2, color: Colors.red),
                  ),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.red,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),

Stadium Border Using TextButton

textbutton stadiumborder
In this example, you will use TextButton for making StadiumBorder. Use style property with ElevatedButton.styleFrom().


TextButton(
                onPressed: () {},
                child: Text(
                  'TextButton',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  primary: Colors.red,
                  shape: StadiumBorder(),
                ),
              ),

StadiumBorder Using TextButton II


              TextButton(
                onPressed: () {},
                child: Text(
                  'TextButton',
                  style: TextStyle(
                    color: Colors.red,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 2,
                      color: Colors.red,
                    ),
                  ),
                ),
              ),

stadium border flutter
Most of the apps use StadiumBorder like above. Showing trending, hot or new categories on a horizontal list.


   TextButton(
                onPressed: () {},
                child: Text(
                  '#Trending',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  primary: Colors.red,
                  shape: StadiumBorder(),
                ),
              ),

Let’s show the outline of TextButton with StadiumBorder.


 TextButton(
                onPressed: () {},
                child: Text(
                  '#Trending',
                  style: TextStyle(
                    color: Colors.red,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 2,
                      color: Colors.red,
                    ),
                  ),
                ),
              ),

StadiumBorder Using ElevatedButton

stadium border flutter
This time we can use successor of RaisedButton aka ElevatedButton. It also have shape property. Then you know what to do.

     ElevatedButton(
                child: Text("ElevatedButton"),
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  primary: Colors.green,
                  shape: StadiumBorder(),
                ),
              ),


   ElevatedButton(
                child: Text(
                  "ElevatedButton",
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  primary: Colors.white,
                  shape: StadiumBorder(
                      side: BorderSide(width: 2, color: Colors.green)),
                ),
              ),

StadiumBorder Using OutlinedButton

Just like TextButton and ElevatedButton, you can also create StadiumBorder shape with OutlinedButton.


OutlinedButton(
                child: Text("OutlinedButton"),
                onPressed: () {},
                style: OutlinedButton.styleFrom(
                  side: BorderSide(
                    width: 2,
                    color: Colors.orange,
                  ),
                  shape: StadiumBorder(),
                ),
              ),


Let’s create a Flutter project which contains all above examples.

If you are using Visual Studio – you can create project using Flutter Command and open through Visual Studio.

clear your main.dart file and paste the below code.

  • Column widget is used to show widgets in vertical order.
  • SizedBox widget used to make empty space between widgets.
  • You can remove debug banner using this post.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Stadium Border In Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter StadiumBorder Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () {},
                child: Text(
                  'TextButton',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  primary: Colors.red,
                  shape: StadiumBorder(),
                ),
              ),
              TextButton(
                onPressed: () {},
                child: Text(
                  'TextButton',
                  style: TextStyle(
                    color: Colors.red,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 2,
                      color: Colors.red,
                    ),
                  ),
                ),
              ),
              TextButton(
                onPressed: () {},
                child: Text(
                  '#Trending',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  primary: Colors.red,
                  shape: StadiumBorder(),
                ),
              ),
              SizedBox(
                height: 8,
              ),
              TextButton(
                onPressed: () {},
                child: Text(
                  '#Trending',
                  style: TextStyle(
                    color: Colors.red,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 2,
                      color: Colors.red,
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 8,
              ),
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 10,
                ),
                decoration: ShapeDecoration(
                  color: Colors.red,
                  shape: StadiumBorder(),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              SizedBox(
                height: 8,
              ),
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 10,
                ),
                decoration: ShapeDecoration(
                  color: Colors.red,
                  shape: StadiumBorder(
                    side: BorderSide(
                      width: 6,
                      color: Colors.green[200]!,
                    ),
                  ),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              SizedBox(
                height: 8,
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
                decoration: ShapeDecoration(
                  shape: StadiumBorder(
                    side: BorderSide(width: 2, color: Colors.red),
                  ),
                ),
                child: Text(
                  'Container',
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.red,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              ElevatedButton(
                child: Text("ElevatedButton"),
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  primary: Colors.green,
                  shape: StadiumBorder(),
                ),
              ),
              ElevatedButton(
                child: Text(
                  "ElevatedButton",
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  primary: Colors.white,
                  shape: StadiumBorder(
                      side: BorderSide(width: 2, color: Colors.green)),
                ),
              ),
              OutlinedButton(
                child: Text("OutlinedButton"),
                onPressed: () {},
                style: OutlinedButton.styleFrom(
                  side: BorderSide(
                    width: 2,
                    color: Colors.orange,
                  ),
                  shape: StadiumBorder(),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

Flutter Machine Learning App Tutorial – Dog vs Cat Detector

flutter machine learning app
In this post, you will make a Flutter Machine Learning App – Actually Dog VS Cat Detector.

Don’t worry, there are no complex mathematical calculations or any other works. without wasting time, let’s start.

okay… but some basics first.

What is Machine Learning?

In simple words, Machine learning is a branch of Artificial Intelligence, helps systems to learn from experience like human beings. They learn from data and predict the output and improve themselves. Companies like Google, Facebook, and Amazon are making use of it.
For example: Recommendation Engines, Email spam filtering.

Types of Machine Learning

    1. Supervised Learning.
    2. Unsupervised Learning.
    3. Reinforcement Learning.

I am not going to talk about these machine learnings except Supervised Learning.

Supervised Learning

It’s like teaching a child, for example mom showing images of animals and teaches which is a dog and a which is a cat. Just like this Machine learning algorithm is provided with lots of labeled data and later it will predict the output based on the input.
Dog vs Cat Detector is an example of Supervised Learning.

Google TeachableMachine

It’s a web-based tool that helps to train models without any coding. For beginners, it’s really helpful. The teachable machine supports models based on images, sounds, and poses and you can freely use the models in your site, app, and more.

Kaggle

An online community for machine learners and data scientists. It offers more than 19,000 public datasets and 200,000 public notebooks to do your data science works.

TensorFlow

It’s a Machine learning – open source library made by Google Brains Team. It assists beginners or experts to create machine learning models.

How To Make A Flutter Machine Learning App Which detects Dog or Cat? – In Simple Steps.

    1. go to Kaggle.com and download Cat and Dog datasets.
    2. Using the datasets, make model using Google teachable machine.
    3. Import the model in Flutter app.
    4. Tensorflow lite package detects given image containing a dog or cat.

Flutter Machine Learning App – Dog vs Cat Detector- Step by step tutorial

Flutter Machine Learning App
We will make an app like above. How is it? looking nice.

Okay. First of all, let’s make a Machine learning model.

  • As a first step, we need to download Cat and Dog dataset from
    Kaggle.com.

  • Now register using your google or your email.
  • Complete registration using by providing full name and agreeing to Privacy and terms.

  • Click on search part, and type Cat and Dog.

  • click on Cat and Dog dataset from the list.

  • It will show a detailed page of Cat and Dog Dataset.
  • Click on the Download button. Now the archive.zip will be downloaded.

      • Extract the zip file.

      • Inside the archive directory, there are 2 sets. testing_set and training_set.
      • Training Set is for training the model and testing set for testing the model. So simple.
      • In these directories, you will get Cat and Dog images.

Using these images, we can make the model.

      • Click on Get Started

      • Select Image Project.

      • Choose Standard Image Model.

      • Change Class 1 to Dog, and Class 2 to Cat .
      • Yes, we are labeling it.

      • You need to upload dog images, in Dogs class.
      • So click on the upload button.

      • Open the training_set directory of Dog, and select all images and click on Open.

      • It takes time to load all images.

      • Just like Dogs, you need to upload Cats images in Cats class from training_set directory.
      • It’s better to keep same amount of images in both sets, but it won’t change the result that much if one set has 5 extra images.

      • Click on Train Model.
      • Using the given images, it will train the model.
      • You can change the additional settings, if you want. But now this is enough.

      • Wait for 50 epoch to complete.

      • Model is completely trained by Google teachable Machine.

      • Let’s preview the model using a dog image from test_set.
      • Choose File option, upload or drag and drop image.

      • Select the image and click open button.

      • Model predicted Successfully. Use any cat image and check it out.

      • For Using this model in apps, you need to export it.
      • Click on Export Model.

      • Click on Download My Model.

      • After a few seconds, converted_tflite.zip file will be downloaded

      • Extract the converted_tflite.zip file.

      • Inside converted_tflite directory, you can see there are two files. Open labels.txt

      • We need to remove 0 and 1.
      • Why are we removing it?
      • At the end, we need to show It’s a Cat or It’s a Dog based on the detection. If we didn’t remove the 0,1 and also the space too. It will end up like this: It’s a 1 Cat or It’s a 0 Dog.

      • Save the labels.txt file like above.

So Let’s create a Flutter project. If you haven’t installed Flutter – Read this tutorial

If you are using

      1. Android Studio – Create Project
      2. Visual Studio – If you have installed plugin and set up the SDK like above tutorial. Use Ctrl + Shift + P -> Flutter: New Application Project or
        Create Project Using this Flutter Command and open project using Visual Studio.

project name: flutter_machine_learning_dogvscat.

      • Create an assets directory, copy and paste labels.txt and model_unquant.tflite.

          • Open pubspec.yaml file and paste below dependencies. I am using 2.12 Dart, Means Null safety is turned on.
            google_fonts: ^2.1.0
            image_picker: ^0.8.3+3
            tflite: ^1.1.2
          
          

      • Add Assets directory in pubspec.yaml file.

      • Open Android/app/build.gradle, and paste the following inside android block.
      aaptOptions {
              noCompress 'tflite'
              noCompress 'lite'
          }
      
      

      flutter tensorflow lite requirements

      • Change minSdkVersion to 19

      • For iOS users, You need to add below contents in ios/runner/info.plist file, For ImagePicker.
      NSPhotoLibraryUsageDescription
      	Need to take Picture from Gallery
      	NSCameraUsageDescription
      	Need to take Picture using Camera
      
      • Let’s clear main.dart file and create a Stateful Widget named MachineLearningApp.
      import 'dart:io';
      import 'package:image_picker/image_picker.dart';
      import 'package:flutter/material.dart';
      import 'package:google_fonts/google_fonts.dart';
      import 'package:tflite/tflite.dart';
      import '../constants.dart';
      
      void main() => runApp(
            MaterialApp(
              home: MachineLearningApp(),
            ),
          );
      
      class MachineLearningApp extends StatefulWidget {
        const MachineLearningApp({ Key? key }) : super(key: key);
      
        @override
        _MachineLearningAppState createState() => _MachineLearningAppState();
      }
      
      class _MachineLearningAppState extends State {
        @override
        Widget build(BuildContext context) {
          return Container(
            
          );
        }
      }
      
      
      • To avoid squiggly red line under ../constants.dart, create a constants.dart file and paste the below code.
      import 'package:flutter/material.dart';
      
      var bold = FontWeight.bold;
      //Black color overlay 
      var filter = ColorFilter.mode(
        Colors.black.withOpacity(0.6),
        BlendMode.darken,
      );
      
      • filter used to create black overlay over the image.
      • First of all, we need to load our model and labels to Tflite.
      class _MachineLearningAppState extends State<MachineLearningApp> 
      {
      
        @override
        void initState() {
          super.initState();
          loadModelData().then((output) {
      //after loading models, rebuild the UI.
            setState(() {});
          });
        }
      
        loadModelData() async {
      //tensorflow lite plugin loads models and labels.
          await Tflite.loadModel(
              model: 'assets/model_unquant.tflite', labels: 'assets/labels.txt');
        }
      
      
      
        @override
        Widget build(BuildContext context) {
          return Container(
            
          );
        }
      }


      Let’s start building the UI. So, first, put any image in the assets directory or you can download our code and copy-paste the image. Here I have used pets.jpg. Implement the below code.

      @override
        Widget build(BuildContext context) {
          Size size = MediaQuery.of(context).size;
      
          return Scaffold(
            body: SingleChildScrollView(
              child: Column(
                children: [
                  titleContent(size),
                ],
              ),
            ),
          );
        }
      
        Container titleContent(Size size) {
          return Container(
      //contains 55% of the screen height.
            height: size.height * 0.55,
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage("assets/pets.jpg"),
                fit: BoxFit.cover,
      //black overlay filter
                colorFilter: filter,
              ),
            ),
            child: Center(
              child: Column(
                children: [
                  SizedBox(
                    height: 60,
                  ),
                  Text(
                    'Dogs Vs Cats',
                    style: GoogleFonts.roboto(
                      fontSize: 40,
                      color: Colors.white,
                      fontWeight: bold,
                    ),
                  ),
                  Text(
                    'Flutter Machine Learning App',
                    style: GoogleFonts.openSansCondensed(
                      fontWeight: bold,
                      fontSize: 20,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          );
        }
      
      


      Define gallery, camera buttons and take images using ImagePicker. In UI, you need to implement below titleContent() inside the Column.

      
                  SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children:[
                      galleryOrCamera(Icons.camera, ImageSource.camera),
                      galleryOrCamera(Icons.photo_album, ImageSource.gallery),
                    ]
                  )
      
      
      
      • Now you will see the red squiggly line again under the galleryOrCamera. Copy paste or type the below code.
      
      
        MaterialButton galleryOrCamera(IconData icon, ImageSource imageSource) {
          return MaterialButton(
            padding: EdgeInsets.all(14.0),
            elevation: 5,
            color: Colors.grey[300],
            onPressed: () {
              _getImage(imageSource);
            },
            child: Icon(
              icon,
              size: 20,
              color: Colors.grey[800],
            ),
            shape: CircleBorder(),
          );
        }
      
      
      
      
      • Rounded Button’s UI is complete now.
      • Let’s move to it’s functionality – Code need to trigger the ImagePicker, when it’s tapped.
      • Before defining _getImage(), you need to create File and ImagePicker instances inside State class.
      
       final ImagePicker _picker = ImagePicker();
        File? _image;
      
      • ImagePicker (New API) uses XFile instead of PickedFile.
      
      _getImage(ImageSource imageSource) async {
      //accessing image from Gallery or Camera.
          final XFile? image = await _picker.pickImage(source: imageSource);
      //image is null, then return
          if (image == null) return;
      
          setState(() {
            _image = File(image.path);
         
          });
        }
      
      
      
      • Next we need to set the selected image and hide titleContent. Only when image is not null.
      
        _image != null ? testImage(size, _image) : titleContent(size),
      
      
      • Define testImage().
      
      Widget testImage(size, image) {
          return Container(
            height: size.height * 0.55,
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: FileImage(
                  image!,
                ),
                fit: BoxFit.cover,
              ),
            ),
          );
        }
      }
      
      

      flutter machine learning app

      • After implementing these code, just run and select any image.
      • You will get output almost like above.
      • Let’s add Instructions, Submit button and AndroidRide text like below.

      flutter machine learning app

      
          SizedBox(height: 50),
                  Text(
                          '1. Select or Capture the image. \n2. Tap the submit button.',
                          style: GoogleFonts.openSans(fontSize: 16),
                        ),
                        Padding(
                    padding: const EdgeInsets.only(top: 30.0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(horizontal: 60),
                        elevation: 4,
                        primary: Colors.grey[300],
                      ),
                      onPressed:(){},
         //             onPressed: detectDogOrCat,
                      child: Text(
                        'Submit',
                        style: GoogleFonts.roboto(
                          color: Colors.black,
                          fontWeight: bold,
                        ),
                      ),
                    ),
                  ),
                SizedBox(height: 45),
                  Text(
                    'androidride.com',
                    style: TextStyle(
                      fontWeight: bold,
                    ),
                  ),
      
      • Let’s create the main part.
      • Define a _result variable, to hold the output from Tflite.runModelOnImage
      List? _result;
       
      
      • Define DetectDogOrCat method.
      void detectDogOrCat() async {
          if (_image != null) {
            try {
              _result = await Tflite.runModelOnImage(
                path: _image!.path,
                numResults: 2,
                threshold: 0.6,
                imageMean: 127.5,
                imageStd: 127.5,
              );
            } catch (e) {}
      
            setState(() {});
          }
        }
      
      
      • call detectDogOrCat() in submit button onPressed Method. Just like below.
      •  Padding(
                      padding: const EdgeInsets.only(top: 30.0),
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.symmetric(horizontal: 60),
                          elevation: 4,
                          primary: Colors.grey[300],
                        ),
                        onPressed: detectDogOrCat,
                        child: Text(
                          'Submit',
                          style: GoogleFonts.roboto(
                            color: Colors.black,
                            fontWeight: bold,
                          ),
                        ),
                      ),
                    ),
        
      • Set _result to null, then only it shows instructions again and again.
      • _getImage(ImageSource imageSource) async {
            final XFile? _image = await _picker.pickImage(source: imageSource);
        
            if (_image == null) return;
        
            setState(() {
              image = File(_image.path);
              _result = null;
            });
          }
        
      • Hide the instructions, if we get result from detectCatOrDog() method.
      • _result != null
                        ? Text(
                            '$_result', 
                            //style: GoogleFonts.openSansCondensed(
                              //fontWeight: FontWeight.bold,
                             // fontSize: 30,
                            //),
                          )
                        : Text(
                            '1. Select or Capture the image. \n2. Tap the submit button.',
                            style: GoogleFonts.openSans(fontSize: 16),
                          ),
        
      • After submitting a dog image, you will get an output like below.

      flutter machine learning app

      • Extract dog label from the Map and uncomment style.
      Text(
                          'It\'s a ${_result![0]['label']}.',
                          style: GoogleFonts.openSansCondensed(
                            fontWeight: FontWeight.bold,
                            fontSize: 30,
                          ),
                        )
      

      flutter machine learning app

      flutter machine learning app

      • Successfully completed the app.

      Download Source Code


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

6 Ways: Flutter Underline Text Example

flutter underline text

In Flutter, underlining a text is easy. This post has listed 6 ways to make it happen.

Let’s start…

1. How To Underline Text in Flutter?

flutter underline text
Flutter provides a constant value to make underlined text – TextDecoration.underline. Use it as value of decoration inside TextStyle.

  • So remember, decoration: TextDecoration.underline.
Text(
                'Flutter Text Underline Example',
                style: TextStyle(
//creates underlined text.
                decoration: TextDecoration.underline,
                ),
              ),

1.1 Dashed Underline

flutter text style underline
Making a dashed underline is easy with Text widget. You just need to use below code inside TextStyle.

  • decoration: TextDecoration.underline – creates underline Text.
  • decorationStyle: TextDecorationStyle.dashed – Makes the underline to dashed line.
Text(
                'Dashed Underline',
                style: TextStyle(
                  //fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.dashed,
                ),
              ),

1.2. Dotted Underline

For dotted underline, use TextDecorationStyle.dotted.

Text(
                'Dotted Underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.dotted,
                ),
              ),

1.3. Flutter Double Underline Example


If a single underline is not enough for you, want a double underline?. You can use TextDecorationStyle.double inside TextStyle.

Text(
                'Double underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.double,
                ),
              ),

1.4. Flutter Wavy Underline

If you have used word, you may have seen wavy underlines when the content have spelling or grammatical errors. Do you want to make a wavy underline like that using Text widget? use TextDecorationStyle.wavy.

Text(
                ' Wavy underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.wavy,
                ),
              ),

2. How To Increase Space Between Underline And Text In Flutter?

flutter text style underline

The above-mentioned examples don’t have enough space between text and underline. In this and the next example, you can adjust the space between them.

  • Here, the visible text content is shadow of real text content. The real text is invisible due to transparent color.
  • Offset determines the text’s shadow location.
  • Offset second argument controls the vertical space difference.
  • Change -20 with other values and check.
                            Text(
                "Text Underline",
                style: TextStyle(
                  color: Colors.transparent,
                  decorationColor: Colors.red,
                  decorationThickness: 5,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.solid,
                  fontSize: 30,
                  shadows: [
                    Shadow(
                      color: Colors.black,
                      offset: Offset(0, -20),
                    ),
                  ],
                ),
              ),

3. Underline Text Using Container

container text underlined flutter
In this method, You will use Container widget and creates a border at the bottom. This border will act as underline to the Text widget.

  • Here, using bottom border padding value, can increase the space between them.
Container(
                padding: EdgeInsets.only(
                  //using bottom property, can control the space between underline and text
                  bottom: 7,
                ),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.red,
                      width: 2.0,
                    ),
                  ),
                ),
                child: Text(
                  "Text Underline Using Container",
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.black,
                  ),
                ),
              ),

4. Flutter Underline Text Using Text.rich

text.rich underline
Using Text.rich constructor, you can underline the word or character in a sentence or paragraph as you like.

  • Text.rich uses TextSpan to show text, Almost same as Text widget.
  • Using style property, you can create underline.
          Text.rich(
                TextSpan(
                  text: ' Underline using ',
                  style: TextStyle(fontSize: 30),
                  children: [
                    TextSpan(
                      text: 'Text.rich',
                      style: TextStyle(
                        decoration: TextDecoration.underline,
                        fontSize:30,
                      ),
                    ),
                    
                  ],
                ),
              ),

5. Underline text using RichText

richtext underline
This method almost same as Text.rich() method. Here, we will use RichText widget and TextSpan to make the underline.

RichText(
                text: TextSpan(
                    text: "Underline Using ",
                    style: TextStyle(
                      fontSize: 25,
                      color: Colors.black,
                    ),
                    children: [
                      TextSpan(
                        text: 'RichText',
                        style: TextStyle(
                          fontSize: 25,
                          color: Colors.black,
                          decoration: TextDecoration.underline,
                        ),
                      )
                    ]),
              ),

6. Underline Using Divider

underline using divider

This is a simple hack. Divider widget can used to make horizontal lines or separate content. Here Divider widget make a yellow line below the Text widget.

  • indent: amount of empty space to the leading edge.
  • endIndent: amount of empty space to the trailing edge.
 Text(
                'Underline using Divider',
                style: TextStyle(fontSize: 20),
              ),
              Divider(
                color: Colors.yellow,
                thickness: 10,
                indent: 70,
                endIndent: 70,
              ),

7. All In One Example

flutter underline text

In this example, we will create all examples and shown them one by one below.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Text Underline Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Flutter Text Underline Example',
                style: TextStyle(
                  fontSize: 25,
                  decoration: TextDecoration.underline,
                ),
              ),
              SizedBox(
                height: 30,
              ),
              Text(
                'Dashed Underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.dashed,
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                "Dashed Underline - 2",
                style: TextStyle(
                  fontSize: 30,
                  shadows: [
                    Shadow(
                      color: Colors.black,
                      offset: Offset(0, -5),
                    ),
                  ],
                  color: Colors.transparent,
                  decoration: TextDecoration.underline,
                  decorationColor: Colors.red,
                  decorationThickness: 5,
                  decorationStyle: TextDecorationStyle.dashed,
                ),
              ),
              SizedBox(
                height: 30,
              ),
              Text(
                'Dotted Underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.dotted,
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                'Double underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.double,
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                ' Wavy underline',
                style: TextStyle(
                  fontSize: 30,
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.wavy,
                ),
              ),
              SizedBox(
                height: 30,
              ),
              RichText(
                text: TextSpan(
                    text: "Underline Using ",
                    style: TextStyle(
                      fontSize: 25,
                      color: Colors.black,
                    ),
                    children: [
                      TextSpan(
                        text: 'RichText',
                        style: TextStyle(
                          fontSize: 25,
                          color: Colors.black,
                          decoration: TextDecoration.underline,
                        ),
                      )
                    ]),
              ),
              SizedBox(height: 30),
              Text.rich(
                TextSpan(
                  text: ' Underline using ',
                  style: TextStyle(fontSize: 30),
                  children: [
                    TextSpan(
                      text: 'Text.rich',
                      style: TextStyle(
                        decoration: TextDecoration.underline,
                        fontSize: 30,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Container(
                padding: EdgeInsets.only(
                  //using bottom property, can control the space between underline and text
                  bottom: 7,
                ),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.red,
                      width: 2.0,
                    ),
                  ),
                ),
                child: Text(
                  "Text Underline Using Container",
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.black,
                  ),
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                'Underline using Divider',
                style: TextStyle(fontSize: 20),
              ),
              Divider(
                color: Colors.yellow,//color of the divider
                thickness: 10,//thickness of the divider
                indent: 70,
                endIndent: 70,
              ),
            ],
          ),
        ),
      ),
    );
  }
}


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

Flutter Underline Constant Docs

3 Ways To Create Hyperlink Text In Flutter

flutter hyperlink text
In Web, Hyperlink takes us to a web page or any other section of the same webpage. Sometimes, we need to implement hyperlinks in our app. For further reading more content or showing your website or Facebook page.

In this post, you will learn how to create hyperlinks in Flutter.

We already discussed about Clickable Text in Flutter. Recommended to read that first, if you didn’t.

1. HyperLink using Link widget And Url_launcher

flutter hyperlink text
In Flutter 2.0, We got a new Widget – Link Widget. Using url_launcher package and Link widget, you can easily navigate to a web page and also launch different screens in your app.

Before Using the Link widget, you must add url_launcher dependency in pubspec.yaml file.

url_launcher: ^6.0.8

If you are targeting Android Devices which has an API level of 30 and above. Just add this in android/app/src/main/AndroidManifest.xml.

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

<queries>
  <!-- If your app opens https URLs -->
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
  </intent>
  <!-- If your app makes calls -->
  <intent>
    <action android:name="android.intent.action.DIAL" />
    <data android:scheme="tel" />
  </intent>
  <!-- If your app emails -->
  <intent>
    <action android:name="android.intent.action.SEND" />
    <data android:mimeType="*/*" />
  </intent>
</queries>

iOS
Add below code in iOS/Runner/info.plist file.

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>https</string>
  <string>http</string>
</array>

flutter hyperlink text

    • In this example, There are 2 Link widgets. One for launching webpage and other for navigating to a new screen.
    • uri property: specify webpage URL or route.
    • builder : Using this property, you can build the link.
    • target property: By default, it uses LinkTarget.defaultTarget
      • Android: opens the link in the browser or any other related app.
      • iOS: opens the link in the webview for web urls.
      • web: Opens in the same tab where Flutter app is running.
    • uri: Uri.parse(‘/second’) – Flutter checks for routes property defined in MaterialApp and navigate to SecondScreen.
 target: LinkTarget.self

  • You can also use self, blank
  • self: On iOS and Android, opens link in the webview inside the app. Web uses the same tab.
Link(
                  uri: Uri.parse('https://androidride.com'),
                  //target: LinkTarget.self,
                  builder: (context, followLink) {
                    return RichText(
                      text: TextSpan(children: [
                        TextSpan(
                          text: 'Click here: ',
                          style: TextStyle(
                            fontSize: 20,
                            color: Colors.black,
                          ),
                        ),
                        TextSpan(
                          text: 'AndroidRide',
                          style: TextStyle(
                            color: Colors.blue,
                            decoration: TextDecoration.underline,
                            fontWeight: FontWeight.bold,
                            fontSize: 21,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = followLink,
                        ),
                      ]),
                    );
                  }),
            ),
            SizedBox(
              height: 20,
            ),
            Link(
              uri: Uri.parse('/second'),
              builder: (context, followLink) {
                return InkWell(
                  onTap: followLink,
                  child: Text(
                    'Go to Second Screen',
                    style: TextStyle(
                      fontSize: 20,
                      color: Colors.blue,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                );
              },
            ),

complete source code is given below.

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/link.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Hyperlink Text Example',

      routes: {
        '/': (context) => FirstScreen(),
        '/second': (context) => SecondScreen()
      },
    );
  }
}

class FirstScreen extends StatelessWidget {
  const FirstScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Hyperlink Text Using Link Widget'),
      ),
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: Link(
                  uri: Uri.parse('https://androidride.com'),
                  //target: LinkTarget.self,
                  builder: (context, followLink) {
                    return RichText(
                      text: TextSpan(children: [
                        TextSpan(
                          text: 'Click here: ',
                          style: TextStyle(
                            fontSize: 20,
                            color: Colors.black,
                          ),
                        ),
                        TextSpan(
                          text: 'AndroidRide',
                          style: TextStyle(
                            color: Colors.blue,
                            decoration: TextDecoration.underline,
                            fontWeight: FontWeight.bold,
                            fontSize: 21,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = followLink,
                        ),
                      ]),
                    );
                  }),
            ),
            SizedBox(
              height: 20,
            ),
            Link(
//when taps the link, moves to second screen.
              uri: Uri.parse('/second'),
              builder: (context, followLink) {
                return InkWell(
                  onTap: followLink,
                  child: Text(
                    'Go to Second Screen',
                    style: TextStyle(
                      fontSize: 20,
                      color: Colors.blue,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  const SecondScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
//poping the current screen from the stack, Shows First Screen.
            Navigator.pop(context);
          },
          child: Text('Go Back To First Screen'),
        ),
      ),
    );
  }
}


2. Flutter Hyperlink Text Using RichText And url_launcher

flutter hyperlink example
This method also uses Url_launcher package.

url_launcher: ^6.0.8

  • Android 10 and above, import below code in android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

<queries>
  <!-- If your app opens https URLs -->
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
  </intent>
  <!-- If your app makes calls -->
  <intent>
    <action android:name="android.intent.action.DIAL" />
    <data android:scheme="tel" />
  </intent>
  <!-- If your app emails -->
  <intent>
    <action android:name="android.intent.action.SEND" />
    <data android:mimeType="*/*" />
  </intent>
</queries>


 

  • iOS – url_launcher
    Add below code in iOS/Runner/info.plist file.
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>https</string>
  <string>http</string>
</array>

 

  • Using RichText, we can make the hyperlink text.
  • Using TapGestureRecognizer‘s onTap method, we can make it clickable.
  • Using URL launcher’s launch() method, we can open the urls.
RichText(
              text: TextSpan(
                  text: "Hyperlink Example Using RichText & url_launcher",
                  style: TextStyle(
                    color: Colors.blue,
                    decoration: TextDecoration.underline,
                    fontSize: 16,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () async {
                      var url = 'https://androidride.com';
                      if (await canLaunch(url)) {
                        await launch(url);
                      } else {
                        throw 'Could not launch $url';
                      }
                    }),
            ),

Complete source code is given below.

  • if canLaunch(URL) method is true, it launches the url.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hyperlink text example 2'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: RichText(
              text: TextSpan(
                  text: "Hyperlink Example Using RichText & url_launcher",
                  style: TextStyle(
                    color: Colors.blue,
                    decoration: TextDecoration.underline,
                    fontSize: 16,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () async {
                      var url = 'https://androidride.com';
                      if (await canLaunch(url)) {
                        await launch(url);
                      } else {
                        throw 'Could not launch $url';
                      }
                    }),
            ),
          ),
        ),
      ),
    );
  }
}


3. Flutter HyperLink Using flutter_linkify

flutter linkify example

In this example, we will use flutter_linkify package. It turns our text URLs and email address into clickable inline links in texts.

again we use url_launcher package.

url_launcher: ^6.0.8

If you are targeting Android Devices which has an API level of 30 and above. Just add this in android/app/src/main/AndroidManifest.xml.

 

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

<queries>
  <!-- If your app opens https URLs -->
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
  </intent>
  <!-- If your app makes calls -->
  <intent>
    <action android:name="android.intent.action.DIAL" />
    <data android:scheme="tel" />
  </intent>
  <!-- If your app emails -->
  <intent>
    <action android:name="android.intent.action.SEND" />
    <data android:mimeType="*/*" />
  </intent>
</queries>

iOS
Add below code in iOS/Runner/info.plist file.

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>https</string>
  <string>http</string>
</array>

hyperlink using flutter_linkify

  • Here Linkify widget makes https://androidride.com as link in text.
Linkify(
            onOpen: (link) async {
              if (await canLaunch(link.url)) {
                await launch(link.url);
              } else {
                throw 'Could not launch $link';
              }
            },
            text: 'Click the link: https://androidride.com',
                   ),

Complete source code is given below.

import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:url_launcher/url_launcher.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hyperlink Using Flutter_linkify'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Linkify(
            onOpen: (link) async {
              if (await canLaunch(link.url)) {
                await launch(link.url);
              } else {
                throw 'Could not launch $link';
              }
            },
            text: 'Click the link: https://androidride.com',
                   ),
        ),
      ),
    );
  }
}


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

Link Widget Docs

Please disable your adblocker or whitelist this site!