Author

admin

Browsing

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.

3 Examples: Draw Circle In Flutter Using CustomPaint

flutter draw circle example
In this post, you will learn how to draw circle using CustomPaint in Flutter.

Before drawing Circle, you must know about CustomPaint widget. Because below examples uses CustomPaint.

What is CustomPaint Widget?

CustomPaint widget gives canvas to draw. For drawing circle, we will use that canvas. This widget provides a property called painter, we need to assign a subclass of CustomPainter.

  • The CustomPainter class gives two methods, paint() and shouldRepaint().
  • When CustomPainter needs to paint, paint() method gets called. Inside paint() method we will implement code to draw circle.
  • Canvas provides lots of draw methods like drawLine(), drawOval, drawRect, drawArc() and drawCircle. There’s more you can check out the documentation.

void drawCircle(
Offset c,
double radius,
Paint paint
)

  • Offset: Where to draw circle center point in the canvas.
  • radius: Radius of the circle.
  • Paint: styling attributes for the circle.

Basics is ready now. So let’s start drawing…

Draw Circle Using CustomPaint – Simple Example

draw cirlce in flutter

  • Scaffold body takes CustomPaint as it’s child with CustomPainter’s subclass.
  • When Flutter started to paint, CustomPainter’s paint() method get called.
  • Using Paint object, made circle color red.
  • Radius of circle is 50.
  • Center of the circle is Offset(0.0, 0.0)

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Draw Circle',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Draw Circle Using CustomPaint'),
        ),
        body: Center(
          child: CustomPaint(
            painter: DrawCircle(),
          ),
        ),
      ),
    );
  }
}

class DrawCircle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint();
    paint.color = Colors.red;

    canvas.drawCircle(Offset(0.0, 0.0), 50, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) 
{//false : paint call might be optimized away.
    return false;
  }
}


Draw Circle inside another Circle Example

draw circle inside another circle flutter

  • Here You will create two Paint objects. One for Red circle and other for yellow circle.
  • Just like the first example, Provided CustomPainter subclass as Scaffold’s body value.
  • Both circle has same center point, different radius will show one circle is inside another circle.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Draw Circle - Second Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Draw Circle Inside Another Circle In Flutter'),
        ),
        body: Center(
          child: CustomPaint(
            painter: DrawCircle(),
          ),
        ),
      ),
    );
  }
}

class DrawCircle extends CustomPainter {
  var paint1 = Paint()..color = Colors.redAccent;
  var paint2 = Paint()..color = Colors.amber[100];
  // ..strokeWidth = 16
  // ..style = PaintingStyle.stroke;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawCircle(Offset(0.0, 0.0), 50, paint1);
    canvas.drawCircle(Offset(0.0, 0.0), 40, paint2);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}


Let’s change the code and make it look like below.
circle inside another circle stroke flutter

  • Add some strokewidth and style using Paint.

 var paint2 = Paint()
    ..color = Colors.amber[100]
    ..strokeWidth = 16
    ..style = PaintingStyle.stroke;

Run now.

3. Gradient Circle Using CustomPaint

gradient circle in flutter

  • Paint class helps to make gradient. Just provide it’s object while drawing circle.
  • This example uses LinearGradient.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Gradient Circle Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Draw Gradient Circle'),
        ),
        body: Center(
          child: CustomPaint(
            painter: DrawCircle(),
          ),
        ),
      ),
    );
  }
}

class DrawCircle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) 
  {
    final paint = Paint()
      ..shader = LinearGradient(colors: [
        Colors.blue,
        Colors.blueGrey,
      ]).createShader(Rect.fromCircle(center: Offset(0.0, 0.0), radius: 50));

    canvas.drawCircle(Offset(0.0, 0.0), 50, paint);

  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}



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

CustomPaint Flutter Docs

3 Vertical Divider Examples in Flutter

vertical divider flutter example
In this post, you will learn how to make a vertical divider in Flutter.

let’s create a simple one.

Simple Vertical Divider Example

divider vertical flutter

If you check the code, you can find out that VerticalDivider is just a SizedBox. You can use Vertical Divider with horizontal ListView.

  • Align widget is used to align the Container to top of the App.
  • In this example, divider height depends on the Container height.
  • Here color of the divider is black.
  • Given 20 empty space above the divider.
  • Divider width is also 20.

import 'package:flutter/material.dart';

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Vertical Divider Example';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatelessWidget(),
      ),
    );
  }
}

class MyStatelessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.topCenter,
      child: Container(
        height: 80,
        padding: const EdgeInsets.all(10),
        child: VerticalDivider(
          color: Colors.black,
          thickness: 3,
          indent: 20,
          endIndent: 0,
          width: 20,
        ),
      ),
    );
  }
}


Properties

Color color : Color of the vertical divider line.

double endIndent: total empty space under the divider.

double indent: sum of empty space on top of the divider.

double thickness: Thickness of the divider

double width: Width of the divider.

Vertical Divider Example 2

divider vertical flutter

Let’s make a red color divider inside Row widget. Yes, just like above image.

  • Row widget aligns Text widgets.
  • Here VerticalDivider’s height depends on the SizedBox’s height.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Vertical Divider Example 2';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatelessWidget(),
      ),
    );
  }
}

class MyStatelessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('May 1, 2021'),
          SizedBox(
            height: 25,
            child: VerticalDivider(
              color: Colors.red,
              thickness: 2,
              indent: 5,
              endIndent: 0,
              width: 20,
            ),
          ),
          Text('Saturday'),
        ],
      ),
    );
  }
}


Vertical Divider Using Container

vertical divider using container
In this example, you will not use VerticalDivider() widget, but you will use Container. It’s really simple to make.

  • Here Align widget used to Align the Padding and VerticalDivider.
  • Depends on Container properties values, you can make your Divider.
  • You can also use other widgets, Just like Container

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  static const String _title = 'Vertical Divider Using Container';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: Align(
          alignment: Alignment.topCenter,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: VerticalDividerWidget(),
          ),
        ),
      ),
    );
  }
}

class VerticalDividerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      width: 3,
      color: Colors.brown,
    );
  }
}


That’s all for now. If you like this post, please share it with your family and Friends. If there is any doubts, please comment.

Thank you for scrolling.

3 TextFormField PlaceHolder Examples In Flutter

textformfield flutter placeholder
In this post, you will learn how to make placeholder in TextFormField and TextField.

Okay.

Let’s set placeholder then.


If you don’t know how to setup Flutter and Create project, you can go to this link. There are some Flutter commands you must know. Go for it too.

Simple TextFormField PlaceHolder Example

textformfield flutter placeholder

  • Below code, we use decoration property inside TextFormField and TextField. You must provide value With InputDecoration
  • Inside InputDecoration, Use hintText to show hint.
         TextFormField(
            decoration: InputDecoration(hintText: 'TextFormField - Hint text'),
          ),
 


         TextField(
            decoration: InputDecoration(hintText: 'TextField - Hint Text'),
          ),
 

2. HintText vs LabelText

hinttext vs labeltext flutter textfield
Most of the people didn’t know the difference between hintText and labelText in Flutter. Above GIF will easily help you to find out the difference.

labelText : it animates the label by default. When the input field(Here TextField) is empty, labelText shows on the top of input field. When it get focus, label moves above the top of input field.

hintText : as the name suggests it just shows a hint to the user and no animation.


TextField(
                decoration: InputDecoration(labelText: 'labelText'),
              ),
              TextField(
                decoration: InputDecoration(hintText: 'hintText'),
              ),
              TextField(
                decoration:
                    InputDecoration(hintText: 'both', labelText: 'both'),
              ),

3. Multiline TextFormField with PlaceHolder example

multiline textformfield flutter placeholder
Sometimes, our app needs a multiline input for taking feedback and other detailed information. In this example, You will make a multiline TextFormField.

  • In this example, you will use TextFormField wrap With Expanded widget inside Column. That helps to expand the TextFormField inside the Column.
  • If expands:true, then you must set maxLines and minLines to null. Otherwise an error thrown.
  • expands:true makes TextField or TextFormField will expands to fill the parent(here Expanded).

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter ',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Column(
          children: [
            Expanded(
              child: TextFormField(
                expands: true,
                maxLines: null,
                minLines: null,
                decoration: InputDecoration(labelText: 'comment'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Rounded Border TextFormField with PlaceHolder example

custom textformfield flutter placeholder
Most of the apps are using rounded border TextFormField nowadays. In flutter it’s easy to make one like above.

  • Here you will use Container around TextFormField
  • Container used to make rounded corners and green background.
  • Flutter Padding Widget
  • Used BoxDecoration inside container to make circular rounded borders.

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('TextFormField PlaceHolder example'),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: 20,
              vertical: 20,
            ),
            decoration: BoxDecoration(
                color: Colors.green.shade300,
                borderRadius: BorderRadius.circular(36)),
            child: TextFormField(
              cursorColor: Colors.white,
              style: TextStyle(
                color: Colors.white,
              ),
              decoration: InputDecoration.collapsed(
                hintStyle: TextStyle(
                  color: Colors.white,
                ),
                hintText: 'Enter something',
              ),
            ),
          ),
        ),
      ),
    );
  }
}


Form Validation Example

flutter login page with validation background image

I have previously talked about this, you can use this link for detailed information.

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

6 Flutter Circle Avatar Widget Examples With Tutorial

flutter circleavatar example
Do you want to make a circular Image icon like in social media apps?

Use CircleAvatar, You can also use Container and other widgets.

But In this post, I am talking about CircleAvatar.

Let’s check it out what will you learn in this post.

Image in Circle Shape Example – Using CircleAvatar

image in circle avatar widget flutter
In this example, you will use NetworkImage widget for showing Image. If you are a real beginner, Use this post to create a Flutter project or you can use Flutter command to create project and open it in Visual Studio Code.

  • Align widget used to align the CircleAvatar to Center
  • By default, CircleAvatar radius size is 20. It’s okay for ListView item. For this example, I increased the size of radius to 50. you can delete that line and check.
  • NetworkImage shows the Image based on the given URL.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter CircleAvatar Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('CircleAvatar - NetworkImage Example'),
        ),
        body: Align(
          alignment: Alignment.topCenter,//aligns CircleAvatar to Top Center.
          child: CircleAvatar(
            radius: 50,//radius is 50
            backgroundImage: NetworkImage(
                'https://cdn.pixabay.com/photo/2015/03/03/20/42/man-657869_1280.jpg'),//image url
          ),
        ),
      ),
    );
  }
}


CircleAvatar Properties

1.backgroundColor: Use this property to fill the circle with color. If backgroundColor is not given, CircleAvatar uses a theme based color.

2.backgroundImage: Using backgroundImage property, You can set Image. Above example, uses NetworkImage. But you can also use FileImage, AssetImage, etc.

3.child: child property used set the widget inside the circle Avatar. Using this property, you can set Image, Icon or Text or any other Widget.

4.foregroundColor: It determines color of the text or Icon inside CircleAvatar.

5.foregroundImage: Foreground image of the CircleAvatar.

6.maxRadius: It determines maximum radius of the CircleAvatar.

7.minRadius: Decides the minimum radius of the CircleAvatar.

8.onBackgroundImageError: Callback released when background image loading fails.

9.onForegroundImageError: Callback executes when foreground Image loading fails.

10.radius: The size of the avatar (half of the diameter). Default size is 20 logical pixels.

Flutter CircleAvatar AssetImage Example

flutter circleavatar assetimage

  • In this example, Let’s use AssetImage widget and load image from app resources.

image in assets directory

  • First create an assets directory, and put your image in it. Just like above.

  assets:
    - assets/

  • Open the pubspec.yaml file, and add assets/ like above. Then only app can access Assets directory.
  • In dart code, you will use AssetImage and specify the path of the image.
  • Here Align used to align the Widget to topCenter. For an empty space around the CircleAvatar – Use Padding.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter CircleAvatar Image Asset Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Circle Avatar AssetImage Example'),
        ),
        body: Align(
          alignment: Alignment.topCenter,//aligns to topCenter
          child: Padding(//gives empty space around the CircleAvatar
            padding: const EdgeInsets.all(8.0),
            child: CircleAvatar(
              radius: 35,//radius is 35.
              backgroundImage: AssetImage('assets/environment.jpg'),//AssetImage loads image URL.
            ),
          ),
        ),
      ),
    );
  }
}


Flutter Circle Avatar Text Example

text inside circleavatar
How to fit text inside CircleAvatar Widget?

CircleAvatar provides a property called child helps to set Text inside of it.

okay…Let’s do that.

  • Row widget : helps to horizontally align both CircleAvatar widgets.
  • SizedBox: gives empty space between CircleAvatar widgets.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter CircleAvatar Text Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter CircleAvatar Text Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(//aligns children to Center.
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              CircleAvatar(
                child: Text(
                  'S',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                backgroundColor: Colors.orange,
              ),
              SizedBox(
                width: 5.0,//empty space between CircleAvatar widgets.
              ),
              CircleAvatar(
                child: Text(
                  'Sun',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                backgroundColor: Colors.red,
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Flutter Icon With Circle Background – Using CircleAvatar

circleavatar widget icon
Let’s use icon instead of image or Text in CircleAvatar.

  • GestureDetector is used to listen for the tap events. If user tapped, it will print “icon tapped” in terminal.
  • Here you will use child property to set the Icon.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter CircleAvatar Icon Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter CircleAvatar Icon Example'),
        ),
        body: Align(
          alignment: Alignment.topCenter, //aligns to topCenter.
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: GestureDetector(
              //listening tap events
              onTap: () {
                print('icon tapped');
              },
              child: CircleAvatar(
                child: Icon(
                  Icons.search,
                  color: Colors.white,
                ),
                backgroundColor: Color(0xFF47b881),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


Flutter Circle Avatar Border Example

circleavatar border flutter

  • Here you will use two CircleAvatar widgets. One for border and other for image.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter CircleAvatar Border Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter CircleAvatar Border Example'),
        ),
        body: Align(
          alignment: Alignment.topCenter,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: CircleAvatar(
              //border
              radius: 110,
              backgroundColor: Colors.brown,
              child: CircleAvatar(
                radius: 100,
                backgroundImage: NetworkImage(
                    'https://cdn.pixabay.com/photo/2017/09/27/15/52/man-2792456_1280.jpg'),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Flutter FB Story Icon Example – Multiple Border Using CircleAvatar

Flutter FB Story Icon - multiple border using circleavatar

Let’s make an Icon like in Facebook Stories.

  • Here you will use 3 CircleAvatars.1: Blue Color, 2: White Color, and 3: for Image.
  • Radius of each is different.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter FB Story Icon ex',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter FB Story Icon ex'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: CircleAvatar(
              radius: 135,
              backgroundColor: Colors.blue,
              child: CircleAvatar(
                radius: 125,
                backgroundColor: Colors.white,
                child: CircleAvatar(
                  radius: 115,
                  backgroundImage: NetworkImage(
                      'https://cdn.pixabay.com/photo/2018/01/15/07/52/woman-3083390_1280.jpg'),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


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

For more info: Flutter CircleAvatar Docs

Please disable your adblocker or whitelist this site!