Author

admin

Browsing

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

3 Ways To Make Clickable Text In Flutter

flutter clickable text
In this post, you will learn how to make clickable text in Flutter. Many apps use clickable text in the signup/login form. After completing this tutorial, you can also make one like that.

Let’s go then.

How To Make Text Clickable Using RichText Widget?

flutter text clickable

In this example, You will use the RichText widget. RichText…, just like the name it’s rich in features when compared to a Text widget.

Let’s check it out.

I have already discussed about clickable text in Flutter Notes App

  • TextSpan used to show text inside RichText.
  • Using recognizer property, we can make the text clickable.
  • Cascade notation(..) allows to perform sequence of operations on same object, here TapGestureRecognizer.
  • When the Login text clicked, onTap method gets called.
  • Don’t forget to add this statement : import ‘package:flutter/gestures.dart’;

RichText(
            text: TextSpan(children: [
              TextSpan(
                text: 'Already have account? ',
                style: TextStyle(
                  color: Colors.black,
                ),
              ),
              TextSpan(
                  text: 'Login',
                  style: TextStyle(
                    color: Colors.blue,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      print('Login Text Clicked');
                    }),
            ]),
          ),

The complete source code is given below.


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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Clickable Text Using RichText',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Clickable Text Using RichText'),
        ),
        body: Center(
          child: RichText(
            text: TextSpan(children: [
              TextSpan(
                text: 'Already have account? ',
                style: TextStyle(
                  color: Colors.black,
                ),
              ),
              TextSpan(
                  text: 'Login',
                  style: TextStyle(
                    color: Colors.blue,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      print('Login Text Clicked');
                    }),
            ]),
          ),
        ),
      ),
    );
  }
}
 

Flutter Clickable Text Using InkWell Example

clickable text nkwell
InkWell widget helps to listen for tap events. Wrapping with Text widget we can easily find out the tap events.

  • When text gets clicked, onTap gets called.

InkWell(
            onTap: () {
              print('Text Clicked');
            },
            child: Text('Clickable Text Using InkWell'),
          ),

complete source code is given below.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Clickable Text Using InkWell',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Clickable Text Example'),
        ),
        body: Center(
          child: InkWell(
            onTap: () {
              print('Text Clicked');
            },
            child: Text('Clickable Text Using InkWell'),
          ),
        ),
      ),
    );
  }
}


Flutter Clickable Text Using GestureDetector

text click flutter gesturedetector
Just like InkWell, GestureDetector can also used to listen for tap events. So just wrap Text widget with GestureDetector.

  • When the text tapped, GestureDetector’s onTap method gets called.

GestureDetector(
            onTap: () {
              print('Text Clicked');
            },
            child: Text('Clickable Text Using GestureDetector'),
          ),

Complete source code given below.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Clickable Text Using GestureDetector',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Clickable Text Example'),
        ),
        body: Center(
          child: GestureDetector(
            onTap: () {
              print('Text Clicked');
            },
            child: Text('Clickable Text Using GestureDetector'),
          ),
        ),
      ),
    );
  }
}


That’s all for now.

If you like this post, please share it with your family and friends. If you got any other ways, feel free to comment.
Thank you.

RichText Widget Docs

4 Ways To Set Background Color Of A Screen In Flutter

set background color in flutter
UI/UX has an importance in your app’s success. A likable user interface can win customers’ trust and love. Therefore sometimes you need to change the default look of the app. So in this post, as a first step, you will learn how to set background color in Flutter.

In Flutter, you can achieve a simple thing in different ways. setting background color too.

Let’s check it out, then.

1. How To Set Background Color Using scaffoldBackgroundcolor property

flutter background color
Scaffold widget provides backgroundColor property to change the background color. By default, it uses Theme.scaffoldBackgroundColor.

  • You can use Colors class values or hex code values.
  • Use hex code like this: 0xff+Hex Code

Scaffold(
         backgroundColor: Color(0xfff57d7c),
         //backgroundColor: Colors.red,

...)

Complete source code is given below.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color(0xfff57d7c),
        // backgroundColor: Colors.red,
        body: Center(
          child: Text(
            'Set Background Color Example',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }
}

2. Set Background Color Using MaterialApp property

flutter materialapp background color
In this example, we will use scaffoldBackgroundColor to change background color. It affects all scaffolds in your app.


MaterialApp(
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.orange,
      ),
      home: MyApp(),
    )

The complete source code is given below.


import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.orange,
      ),
      home: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Set Background Color Example 2'),
      ),
      body: Center(
        child: Text(
            'Set Background Color Using \n\nscaffoldBackgroundColor Property'),
      ),
    );
  }
}


3. Change Background Color Using Theme class

background color using theme
In this example, You will use Theme class. Using Theme class, You can change background color using scaffoldBackgroundColor property.

  • copyWith() method takes properties which need to change and return new object.

Theme(
        data: Theme.of(context).copyWith(
          scaffoldBackgroundColor: Colors.indigo,
        )
....

Complete Source code is given below.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Theme(
        data: Theme.of(context).copyWith(
          scaffoldBackgroundColor: Colors.indigo,
        ),
        child: Scaffold(
          body: Center(
            child: Text(
              'Set Background Color Using Theme Class',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}


4.1 Set Background Color Using Container


In this example, we will use Container widget to set background color. Container uses complete height and width of the screen.


Scaffold(
        body: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.yellow,
          child: Center(child: Text('Set Background Color Using Container')),
        ),
      ),

Complete Source code is given below.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.yellow,
          child: Center(child: Text('Set Background Color Using Container2')),
        ),
      ),
    );
  }
}


4.2 Set Background Color Using Container and SizedBox

  • SizedBox.expand() become large as parent allows.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SizedBox.expand(
          child: Container(
            color: Colors.yellow,
            child: Center(
              child: Text('Set Background Color Using Container & SizedBox'),
            ),
          ),
        ),
      ),
    );
  }
}


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

2 Ways To Break Text Line In Flutter

how to break text line in flutterShowing large chunks of text without break in app is visually unappealing. Users might feel painful to read.
Most of the users scan the content at an initial glance, if they don’t find what they want, most of the time, they will click back.

So It’s our developers’ task to make the app’s content easy to read and make it visually attractive.

This post describes two simple but effective ways to break the content.

How To Break Text Line In Flutter? – Using New Line character

flutter text line break
For those who don’t know new line. \n is the new line character. Using this character, we can easily make a new line.

Let’s create a simple example like above.


Text('Like\nAndroidRide\n\nShare Posts')

  • When first \n added, “AndroidRide” text moved to next line.
  • When \n added twice, content placed to second line.

Here is the full source code.


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 Line Break Example 1'),
        ),
        body: Center(
          child: Text('Like\nAndroidRide\n\nShare Posts'),
        ),
      ),
    );
  }
}


How to break Text line using triple quotes?

text line break in flutter using triple quotes
In this example, you will learn how to break text line using triple quotes.

It’s another easy method, you don’t need to do anything extra. Just place your content inside the triple quotes like below.

  • ”’Content”’
  • Padding used to get some white space around the Text widget.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final dataString =
      '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.  

Pretium quam vulputate dignissim suspendisse in est. Ipsum dolor sit amet consectetur adipiscing elit. Urna porttitor rhoncus dolor purus non enim praesent elementum. Arcu ac tortor dignissim convallis. Sed libero enim sed faucibus. Amet venenatis urna cursus eget. 

Aliquet porttitor lacus luctus accumsan tortor. Suscipit adipiscing bibendum est ultricies. Dolor magna eget est lorem ipsum. Ac tortor dignissim convallis aenean et tortor. 
 ''';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Text Line Break Example 2'),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Text(dataString),
          ),
        ),
      ),
    );
  }
}

That’s all for now. If you got any other methods, feel free to share with us.

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

Thank You.

2 Examples: Scan, Generate & Share QR Code In Flutter

scan qr code flutter generate example
QR code is a special type of barcode. Most of the apps we use, have QR code scanning feature.

So if you are planning to add QR code reading or generating feature.

Then you are in the right place.

Scan QR Code In Flutter Example

flutter read qr code
Let’s create a simple QR scanning app using qr_code_scanner package. This package also provides

  • Turning on/off flashlight
  • Flip camera

You can achieve these features in just one line of code.

I assume you have created Flutter project, let’s add QR code dependency in pubspec.yaml file.

  • Dependency requires Android API 21. For iOS devices, requires iOS 8.

cupertino_icons: ^1.0.2
qr_code_scanner: ^0.5.1

Indentation is important.

For iOS devices


io.flutter.embedded_views_preview

NSCameraUsageDescription
Need to access Camera for scanning QR codes

In main.dart file, just import this dependecy in your code.


import 'package:qr_code_scanner/qr_code_scanner.dart';

  • In this example, There are 2 sections.
  • First section which holds QRView, flip camera and flash icons.
  • 2nd section for displaying QR code data.

Let’s learn about QRView widget.

QRView

QRView widget scans the QR code and return its information.

  • onQRViewCreated: When the view get’s created, it invokes with QRViewController. So we will use this property to get the QR code data and display it in Text.
  • overlay: Use this property to make a certain scan area. Using QrScannerOverlayShape, we can make a rectangular area.
    • Teal color used for border color.
    • As cutOutSize, we will use 80% of the width.
  • controller.flipCamera(): Flip FrontCamera/Backcamera.
  • controller.toggleFlash(): Turn on/off Flashlight

import 'dart:io';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scan QR Code - Flutter Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScanQRPage(),
    );
  }
}

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

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

class _ScanQRPageState extends State {
  final GlobalKey qrKey = GlobalKey();
  late QRViewController controller;
  Barcode? result;
//in order to get hot reload to work.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    } else if (Platform.isIOS) {
      controller.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Scan QR Code - Flutter Example'),
      ),
      body: Column(
        children: [
          Expanded(
            flex: 4,
            child: Stack(
              children: [
                QRView(
                  key: qrKey,
                  onQRViewCreated: onQRViewCreated,
                  overlay: QrScannerOverlayShape(
//customizing scan area
                    borderWidth: 10,
                    borderColor: Colors.teal,
                    borderLength: 20,
                    borderRadius: 10,
                    cutOutSize: MediaQuery.of(context).size.width * 0.8,
                  ),
                ),
                Positioned(
                  left: 0.0,
                  right: 0.0,
                  bottom: 0.0,
                  child: Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Colors.black26,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        IconButton(
                            icon: Icon(
                              Icons.flip_camera_ios,
                              color: Colors.white,
                            ),
                            onPressed: () async {
                              await controller.flipCamera();
                            }),
                        IconButton(
                            icon: Icon(
                              Icons.flash_on,
                              color: Colors.white,
                            ),
                            onPressed: () async {
                              await controller.toggleFlash();
                            })
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.all(8.0),
              width: double.infinity,
              color: Colors.white,
              child: Center(
                child: result != null
                    ? Column(
                        children: [
                          Text('Code: ${result!.code}'),
                          SizedBox(
                            height: 8.0,
                          ),
                          Text('Format: ${result!.format}'),
                        ],
                      )
                    : Text('Scan Code'),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void onQRViewCreated(QRViewController p1) 
{
//called when View gets created. 
    this.controller = p1;

    controller.scannedDataStream.listen((scanevent) {
      setState(() {
//UI gets created with new QR code.
        result = scanevent;
      });
    });
  }

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


QR Code Generator & Share Example

qr code generator share

In this example, You will learn how to generate a QR Code from given data in TextField using qr_flutter and Share it using share_plus.

path_provider: Used for finding usually used locations on filesystem.

Let’s add these packages in as dependencies in pubspec.yaml file.


  qr_flutter: ^4.0.0
  path_provider:
  share_plus: ^2.1.2

Use flutter pub get command.

Import these lines in your main.dart file.


import 'package:qr_flutter/qr_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

  • QrImage widget creates code using value in data property.
  • First ElevatedButton, resets UI with new QR code.
  • Share ElevatedButton creates a QR code image in app’s directory and share it with using Share_plus.
  • This example, stores qr image in app documents directory. You can also use temporary directory.
  • Share.shareFiles(): For sharing QR code image, we need to pass path of the image, type and text for sharing.

import 'dart:typed_data';
import 'dart:ui';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter QR Code Generator With Share',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: QRGeneratorSharePage(),
    );
  }
}

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

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

class _QRGeneratorSharePageState extends State {
  final key = GlobalKey();
  String textdata = 'androidride.com';
  final textcontroller = TextEditingController();
  File? file;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text('QR Code Generator With Share Example'),
      ),
      body: Column(
        children: [
          RepaintBoundary(
            key: key,
            child: Container(
              color: Colors.white,
              child: QrImage(
                size: 300,//size of the QrImage widget.
                data: textdata,//textdata used to create QR code
              ),
            ),
          ),
          SizedBox(
            height: 50,
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: textcontroller,
            ),
          ),
          ElevatedButton(
            child: Text('Create QR Code'),
            onPressed: () async {
              setState(() {
//rebuilds UI with new QR code
                textdata = textcontroller.text;
              });
            },
          ),
          ElevatedButton(
            child: Text('Share'),
            onPressed: () async {
              try {
                RenderRepaintBoundary boundary = key.currentContext!
                    .findRenderObject() as RenderRepaintBoundary;
//captures qr image 
                var image = await boundary.toImage();

                ByteData? byteData =
                    await image.toByteData(format: ImageByteFormat.png);

                Uint8List pngBytes = byteData!.buffer.asUint8List();
//app directory for storing images.
                final appDir = await getApplicationDocumentsDirectory();
//current time
                var datetime = DateTime.now();
//qr image file creation
                file = await File('${appDir.path}/$datetime.png').create();
//appending data
                await file?.writeAsBytes(pngBytes);
//Shares QR image
                await Share.shareFiles(
                  [file!.path],
                  mimeTypes: ["image/png"],
                  text: "Share the QR Code",
                );
              } catch (e) {
                print(e.toString());
              }
            },
          )
        ],
      ),
    );
  }
}


flutter qr code

This QR image created using the above example.

That’s all for now. If you like this post, please share it.

Please disable your adblocker or whitelist this site!