Author

admin

Browsing

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

5 Flutter Carousel Slider Examples With Tutorial

flutter carousel slider example
In this post, you will learn about the Flutter carousel_slider package. Using this package you can easily create your own image carousel or any other widget carousel.

Also Recommend to read this tutorial: Flutter Swiper Example

okay… Let’s start with a simple example.

s

The carousel_slider package supports Android, iOS, Web, and Desktop. So let’s show it through the carousel.

Let’s create a Flutter project in Android Studio or Visual Studio.

open pubspec.yaml file, and paste the package dependency.


carousel_slider: ^3.0.0
cupertino_icons: ^1.0.0

Open the main.dart file and paste the below code.

  • CarouselSlider items property holds the children.
  • In this example, childrens are just Text widget wrapped with Padding widget.
  • By default, autoplay set to false.
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Carousel Slider',
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Carousel Slider Example'),
        ),
        body: CarouselSlider(
          items: [
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Text('Android'),
            ),
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Text('iOS'),
            ),
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Text('Desktop'),
            ),
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Text('Web'),
            )
          ],

          //Slider Container properties
          options: CarouselOptions(
            autoPlay: true,
          ),
        ),
      ),
    );
  }
}

carousel slider builder example

In this example, we will create the same above app using CarouselSlider.builder().

open pubspec.yaml file, and paste the package dependency.


carousel_slider: ^3.0.0
cupertino_icons: ^1.0.0

open main.dart file, and paste the below code.


  • itemCount
    : You need to specify how many items are there on your carousel.
  • itemBuilder will help you to build each carousel item.
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

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

class MyApp extends StatelessWidget 
{
  final items = ["Android", "iOS", "Desktop", "Web"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Carousel Slider Builder Example'),
      ),
      body: CarouselSlider.builder(
        options: CarouselOptions(
          height: 100.0,
          autoPlay: true,
        ),
        itemCount: items.length,
        itemBuilder: (context, itemIndex, realIndex) 
        {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(items[itemIndex]),
          );
        },
      ),
    );
  }
}



flutter image carousel slider

Let’s make a Image Slider using Carousel Slider Widget in Flutter. In this example, we load images from internet.

paste the dependency in pubspec.yaml file just like below.


cupertino_icons: ^1.0.0
carousel_slider: ^3.0.0

  • imagesList holds image URL items.
  • CarouselSlider Uses Image.network() to show each URLs.

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

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

class MyApp extends StatelessWidget {
  final List imagesList = [
    'https://cdn.pixabay.com/photo/2017/12/10/14/47/piza-3010062_1280.jpg',
    'https://cdn.pixabay.com/photo/2016/06/07/01/49/ice-cream-1440830_1280.jpg',
    'https://cdn.pixabay.com/photo/2017/12/27/07/07/brownie-3042106_1280.jpg',
    'https://cdn.pixabay.com/photo/2018/02/25/07/15/food-3179853_1280.jpg',
    'https://cdn.pixabay.com/photo/2015/10/26/11/10/honey-1006972_1280.jpg',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Image Carousel Example '),
      ),
      body: CarouselSlider(
        options: CarouselOptions(
          autoPlay: true,
        ),
        items: imagesList
            .map(
              (item) => Center(
                child: Image.network(
                  item,
                  fit: BoxFit.cover,
                ),
              ),
            )
            .toList(),
      ),
    );
  }
}


custom flutter image carousel

Let’s use some CarouselOptions properties and customize your slider.

  • viewportFraction customize the size of the item.
  • enlargeCenterPage: enlarge the centered item if it set to true.

CarouselSlider(
        options: CarouselOptions(
          viewportFraction: 0.6,
          autoPlayAnimationDuration: const Duration(milliseconds: 100),
          autoPlay: true,
          enlargeCenterPage: true,
        ),
        items: imagesList
            .map(
              (item) => Center(
                child: Image.network(
                  item,
                  fit: BoxFit.cover,
                ),
              ),
            )
            .toList(),
      ),

flutter image carousel fullscreen
We will use MediaQuery to find screen height of the device, and specify to carousel slider.

I assume you might paste the dependency in pubspec.yaml, if you don’t, check above example or paste the latest carousel_slider dependency.

  • final height = MediaQuery.of(context).size.height – gets Screen Height of the device.

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

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

class MyApp extends StatelessWidget {
  final List imagesList = [
    'https://cdn.pixabay.com/photo/2020/11/01/23/22/breakfast-5705180_1280.jpg',
    'https://cdn.pixabay.com/photo/2016/11/18/19/00/breads-1836411_1280.jpg',
    'https://cdn.pixabay.com/photo/2019/01/14/17/25/gelato-3932596_1280.jpg',
    'https://cdn.pixabay.com/photo/2017/04/04/18/07/ice-cream-2202561_1280.jpg',
    'https://cdn.pixabay.com/photo/2019/01/14/17/25/gelato-3932596_1280.jpg'
  ];

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Carousel FullScreen Example'),
      ),
      body: CarouselSlider(
        options: CarouselOptions(
          height: height,
          autoPlay: true,
        ),
        items: imagesList
            .map(
              (item) => Container(
                child: Center(
                  child: Image.network(
                    item,
                    fit: BoxFit.cover,
                    height: height,
                  ),
                ),
              ),
            )
            .toList(),
      ),
    );
  }
}


vertical carousel example

  • scrollDirection: Axis.vertical – It changes the scroll direction of Carousel Slider.

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

final List imagesList = [
  'https://cdn.pixabay.com/photo/2020/11/01/23/22/breakfast-5705180_1280.jpg',
  'https://cdn.pixabay.com/photo/2016/11/18/19/00/breads-1836411_1280.jpg',
  'https://cdn.pixabay.com/photo/2019/01/14/17/25/gelato-3932596_1280.jpg',
  'https://cdn.pixabay.com/photo/2017/04/04/18/07/ice-cream-2202561_1280.jpg',

];

final List titles = [
  ' Coffee ',
  ' Bread ',
  ' Gelato ',
  ' Ice Cream ',
];

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

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

class _MyAppState extends State {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Vertical Carousel With Image'),
        ),
        body: CarouselSlider(
          options: CarouselOptions(
            autoPlay: true,
            enlargeCenterPage: true,
            scrollDirection: Axis.vertical,
            onPageChanged: (index, reason) {
              setState(
                () {
                  _currentIndex = index;
                },
              );
            },
          ),
          items: imagesList
              .map(
                (item) => Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Card(
                    margin: EdgeInsets.only(
                      top: 10.0,
                      bottom: 10.0,
                    ),
                    elevation: 6.0,
                    shadowColor: Colors.redAccent,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30.0),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(
                        Radius.circular(30.0),
                      ),
                      child: Stack(
                        children: [
                          Image.network(
                            item,
                            fit: BoxFit.cover,
                            width: double.infinity,
                          ),
                          Center(
                            child: Text(
                              '${titles[_currentIndex]}',
                              style: TextStyle(
                                fontSize: 24.0,
                                fontWeight: FontWeight.bold,
                                backgroundColor: Colors.black45,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              )
              .toList(),
        ),
      ),
    );
  }
}


image carousel with indicator
In this final example, you will create an image carousel with indicator.

Do not forget to add dependency in pubspec.yaml,


carousel_slider: ^3.0.0  
cupertino_icons: ^1.0.0
  

open main.dart file, paste the below code.

  • When a page or image changes, onPageChanged gets called and sets _currentIndex
  • Using Row’s mainAxisAlignment, property you can change the location of Indicator. Here, I have used mainAxisAlignment: MainAxisAlignment.center – You can change it into MainAxisAlignment.start or any other values.

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

final List imagesList = [
  'https://cdn.pixabay.com/photo/2020/11/01/23/22/breakfast-5705180_1280.jpg',
  'https://cdn.pixabay.com/photo/2016/11/18/19/00/breads-1836411_1280.jpg',
  'https://cdn.pixabay.com/photo/2019/01/14/17/25/gelato-3932596_1280.jpg',
  'https://cdn.pixabay.com/photo/2017/04/04/18/07/ice-cream-2202561_1280.jpg',
];

final List titles = [
  ' Coffee ',
  ' Bread ',
  ' Gelato ',
  ' Ice Cream ',
];

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

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

class _MyAppState extends State {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Carousel with indicator demo'),
        ),
        body: Column(
          children: [
            CarouselSlider(
              options: CarouselOptions(
                autoPlay: true,
                // enlargeCenterPage: true,
                //scrollDirection: Axis.vertical,
                onPageChanged: (index, reason) {
                  setState(
                    () {
                      _currentIndex = index;
                    },
                  );
                },
              ),
              items: imagesList
                  .map(
                    (item) => Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Card(
                        margin: EdgeInsets.only(
                          top: 10.0,
                          bottom: 10.0,
                        ),
                        elevation: 6.0,
                        shadowColor: Colors.redAccent,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30.0),
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.all(
                            Radius.circular(30.0),
                          ),
                          child: Stack(
                            children: [
                              Image.network(
                                item,
                                fit: BoxFit.cover,
                                width: double.infinity,
                              ),
                              Center(
                                child: Text(
                                  '${titles[_currentIndex]}',
                                  style: TextStyle(
                                    fontSize: 24.0,
                                    fontWeight: FontWeight.bold,
                                    backgroundColor: Colors.black45,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: imagesList.map((urlOfItem) {
                int index = imagesList.indexOf(urlOfItem);
                return Container(
                  width: 10.0,
                  height: 10.0,
                  margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentIndex == index
                        ? Color.fromRGBO(0, 0, 0, 0.8)
                        : Color.fromRGBO(0, 0, 0, 0.3),
                  ),
                );
              }).toList(),
            )
          ],
        ),
      ),
    );
  }
}

vertical image slider with indicator
In this example, we just add two properties exactly with above example.


scrollDirection: Axis.vertical,
enlargeCenterPage: true,

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

For more Information: Carousel_Slider

3 Examples: How To Center Appbar Title in Flutter?

how to center appbar title in Flutter

In Flutter, it’s easy to make the AppBar title to center.

Let’s learn about that by doing below examples.

1. How To align AppBar Title To Center?

how to center appbar title flutter
By Default AppBar comes with centerTitle property.

You just need to put true as value, and it will make appbar title into center.

center appbar title flutter result2

...
AppBar(
          title: Text("ANDROIDRIDE"),
          centerTitle: true,
        ),
...

Complete source code is given below.


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
   
   
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("ANDROIDRIDE"),
        ),
        body: Container(
          child: Center(
            child: Text(
              'Center AppBar Title Example',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ),
    );
  }
}


Let’s move on to the next example…

2. How To Make AppBar Title To Center Using Row Widget

center appbar title row example

In this example, you will learn how to use the Row widget and align the title to center. we won’t use centerTitle property here.

  • mainAxisAlignment: MainAxisAlignment.center – It aligns Text widget to center.
  • Using this method, you can change the position of Text however you want.
  • Use padding widget, if it is not aligned well.
 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Row(
            //children align to center.
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("ANDROIDRIDE"),
            ],
          ),
          //menu icon
          leading: IconButton(
            icon: Icon(Icons.menu),
            onPressed: () {},
          ),
          actions: [
            //search icon
            IconButton(
              icon: Icon(Icons.search),
              onPressed: () {},
            )
          ],
        ),
      ),
    );
  }

3. SliverAppBar Center Title Example

sliverappbar center title example
This is not an AppBar Example. SliverAppBar gives extra functionality like animation while scrolling.


@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter SliverAppBar Center Title Example',
      home: Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (context, innerBoxScrolled) {
            return [
              SliverAppBar(
 //appbar size when it fully expanded.
                expandedHeight: 160.0,
                //appbar remains visible after scrolling
                pinned: true,
                floating: false,
                flexibleSpace: FlexibleSpaceBar(
//make title centered.
                  centerTitle: true,
                  title: Text(
                    "ANDROIDRIDE",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 24.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
          
                ),
              ),
            ];
          },
          body: Center(
            child: Text("Flutter SliverAppBar Center Title Example"),
          ),
        ),
      ),
    );
  }

  • expandedHeight: 160.0 – The maximum size of the appbar when it expanded.

sliverappbar title example image

You can easily add an image behind SliverAppBar, using background property. Use the below code inside FlexibleSpaceBar.


background: Image.network(
                    "https://cdn.pixabay.com/photo/2016/05/05/02/37/sunset-1373171_1280.jpg",
                    fit: BoxFit.cover,
                  ),

  • You can also use Image.asset() – if you are loading image from the assets.

That’s all for now. Please share it with your friends and family.
Thank you.

Conclusion

Most of the apps nowadays showing titles at the top and center of the AppBar. So the idea is not new and you can easily set it in Flutter. By default, Flutter comes with what we need, Using first example you can easily understand that. If you want to customize a little bit then you can go for the second one. Third one is SliverAppbar example, which gives an animation look. Depends on your need customize it and use it in your app. Using those three examples, I assume you will learn how to center appbar title in Flutter.

SliverAppBar docs

3 Ways: How To Remove Debug Banner In Flutter?

how to remove debug banner in flutter
Debug banner is annoying

  • while taking a screenshot
  • if any widget behind it

Although it helps us to know it’s in debug mode.

Let’s remove that.

1. Use debugShowCheckedModeBanner with false value inside MaterialApp.

how to remove debug banner in flutter

  • Just use debugShowCheckedModeBanner property with MaterialApp.

just like below.


MaterialApp(
  debugShowCheckedModeBanner: false,
) 

Yes, that’s all you need.

Just put that property in MaterialApp and done. It works for the whole application.
remove debug banner example


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'ANDROIDRIDE',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Remove Debug Banner Example'),
      ),
      body: Center(child: Text('Remove Debug Banner Example')),
    );
  }
}


For becoming a better Flutter developer, you should know the below ones too.

2. Use Flutter Inspector And Remove Banner In Android Studio

flutter inspector - remove debug

  • If you are using Android Studio, you can easily select Flutter Inspector tab available at the right corner.

Flutter Inspector in Android Studio

  • Click on More Actions and select Hide Debug Mode Banner.

Yes..that’s done.

Run and check now.

3. Remove Debug Banner Using Flutter Commands

There are 3 modes available for Flutter App development

  • Debug,
  • Profile,
  • Release,

Debug banner appeared to show developers that the app is in debug mode. In this mode, you can develop, fix bugs and Hot reload the application.

In Profile mode, you can analyze the performance of the Flutter app. Use DevTools, very useful.

You need to make a release version of your app to deploy it in the play store. In this mode, the debug banner will be avoided.

For running release version of your app, use this command

flutter run --release
  • Use real devices rather than emulators or simulators.

Let’s make a build version of the app.

flutter build apk

Check it out now.

Conclusion

While taking a screenshot, or updating a widget behind the debug banner (For example, the cart icon in the e-commerce app). Developers may get irritated due to the debug banner. So, sometimes it’s better to hide. Using the MaterialApp property is one of the easiest ways to remove it. Just one line of code, that’s done. But you can also test the other ways depending on your needs. If any steps I have missed, you can comment below.

8 Flutter Background Image Examples With Tutorials

Flutter background image example
If you are trying to set background image to your Flutter app, then you came to the right place.

Before making one, Most of the below examples, images are loaded from the Assets directory.

So you need to define it in pubspec.yaml. At the same time, You need to create an assets folder and put the image in there.

  assets:
    - assets/


Let’s start with a simple one.

1. How To Add Background Image To Container?

flutter add background image to container

  • Using the decoration property of a Container, we can easily add a background image.
decoration: BoxDecoration(
                       image: DecorationImage(
              image: AssetImage('assets/fitness.jpg'),
              fit: BoxFit.cover,
            ),
          )

Using above code inside Container, You can add Image as background.

Let’s make the above example.

  • In this example, Center Widget used to align the Text Widget.
  • Container’s margin property set free space around Container. You can also use Padding.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Add Background Image To Container Example'),
        ),
        body: Container(
          margin: EdgeInsets.all(8.0),
          child: Center(
            child: Text(
              'FITNESS',
              style: TextStyle(
                backgroundColor: Colors.black38,
                fontSize: 25.0,
                color: Colors.white,
              ),
            ),
          ),
          width: double.infinity, //stretches to maximum width
          height: 200.0,
          decoration: BoxDecoration(
                        image: DecorationImage(
              image: AssetImage('assets/fitness.jpg'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }
}

  • Don’t forget to add assets in pubspec.yaml.

Let’s make rounded corners to Container

set background image rounded container

              decoration: BoxDecoration(
                borderRadius:
                    BorderRadius.circular(10.0), //makes the border circular
                image: DecorationImage(
                  image: AssetImage('assets/fitness.jpg'),
                  fit: BoxFit.cover,
                ),
              ),
  • borderRadius: BorderRadius.circular(10.0) – It makes borders rounded.

2. Flutter background image full-screen Example

In this example, you will learn how to set an image as the background and make it to full screen.

Flutter Image Container full screen example
In this example,

  • constraints: BoxConstraints.expand() – It makes container to use maximum width and height. If width and height values not provided.
  • Using center and Column widgets, Text widgets can align to center.
  • Here, SizedBox just gives some empty space between the Text widgets.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          constraints: BoxConstraints.expand(),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/sky.jpg'),
              fit: BoxFit.cover,
            ),
          ),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  'ANDROIDRIDE',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 35.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                SizedBox(
                  height: 8,
                ),
                Text(
                  'Flutter Image BackGround \n Full Screen Example',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 25.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

3. Flutter Background Image Full Screen Example Using Stack

Above Example, I have used Container to set Image as background. In this one, We will use Stack.

Okay…Let’s do it.

flutter background image full screen stack
In this example,

  • Positioned.fill() – it makes image to fill the entire screen.
  • Using Positioned widget, you can align Widgets in Stack.
class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //resizeToAvoidBottomInset: false,
        body: Stack(
      children: [
        Positioned.fill(
          child: Image(
            image: AssetImage("assets/mystery.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        Positioned(
          top: 330,
          left: 70,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'ANDROIDRIDE',
                style: TextStyle(
                  backgroundColor: Colors.black54,
                  fontSize: 35.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              Text(
                'Flutter background Image Using Stack',
                style: TextStyle(
                  backgroundColor: Colors.black87,
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              )
            ],
          ),
        ),
      ],
    ));
  }
}


Flutter Background Image Blur Example

In Flutter, you can easily make images blur. Let’s use BackdropFilter, ImageFilter.blur() and make this example.

Okay…Let’s see the final output.

flutter bacground image blur backdropfilter

  • BackdropFilter widget won’t give blur effect to its child but beneath it – Here AssetImage
  • Using ImageFilter.blur value, you can control the blur effect.
  • In this example, I have used black color with opacity, this helps viewers to read text easily.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/sky.jpg'),
              fit: BoxFit.cover,
            ),
          ),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'ANDROIDRIDE',
                      style: TextStyle(
                        fontSize: 35.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      'Flutter Background Image Blur Example 1',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 15.0,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Flutter Background Blur Image using Stack.

In this example, you will learn how to make image blur using ImageFiltered Widget.

flutter background blur image using stack

  • In this example, ImageFiltered widget is used to create blur effect.
class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Positioned.fill(
            child: ImageFiltered(
              imageFilter: ImageFilter.blur(
                sigmaX: 10.0,
                sigmaY: 10.0,
              ),
              child: Image(
                image: AssetImage("assets/mystery.jpg"),
                fit: BoxFit.cover,
              ),
            ),
          ),
          Positioned(
            top: 320,
            left: 60,
            child: Column(
              children: [
                Text(
                  'ANDROIDRIDE',
                  style: TextStyle(
                    backgroundColor: Colors.black12,
                    fontSize: 35.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                SizedBox(
                  height: 8,
                ),
                Text(
                  'Flutter Background Blur Image Using Stack',
                  style: TextStyle(
                    backgroundColor: Colors.black12,
                    fontSize: 15.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}


6. Flutter Fullscreen Image Using URL

Actually, this example is not necessary. Because we already did it using AssetImage. Here we just changing with NetworkImage. Sometimes, this may help beginners.

fullscreen image using URL (NetworkImage)

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          constraints: BoxConstraints.expand(),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(
                  'https://images.pexels.com/photos/2102367/pexels-photo-2102367.jpeg'),
              fit: BoxFit.cover,
            ),
          ),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    'ANDROIDRIDE',
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 35.0, color: Colors.white),
                  ),
                ),
                Text(
                  'Flutter Image BackGround Full Screen - NetworkImage',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 15.0,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


How To Add Gradient Over Full Screen Image?

Let’s make a gradient overlay over the image and display it.

flutter gradient on top of image

  • You can set Gradient using gradient property of BoxDecoraion.
  • LinearGradient begin and end property defines where to start and end gradient color.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack(
          children: [
            Container(
              constraints: BoxConstraints.expand(),
              decoration: BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(
                    'https://cdn.pixabay.com/photo/2019/03/13/11/04/copenhagen-4052654_1280.jpg',
                  ),
                ),
              ),
            ),
            Opacity(
              opacity: 0.85,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        Colors.red,
                        Colors.blue,
                      ]),
                ),
              ),
            ),
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'ANDROIDRIDE',
                    style: TextStyle(
                      fontSize: 35.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  Text(
                    'Flutter Background Image Full Screen Gradient ',
                    style: TextStyle(
                      fontSize: 15.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}



Flutter Login Page with Background image

Let’s make a Login page with form validation.

Looks nice. isn’t it?

flutter login page with background image

Validation Demo:

flutter login page with validation

    • Using Form and TextFormFields, It’s easier to make a login page and also helpful to validate the inputs.
    • autofocus:true enables focus on username TextFormField.

text input action next

  • When username is typed and taps on the softkeyboard bottom Right Corner key defined using textInputAction: TextInputAction.next. It calls onFieldSubmitted(), and Change focus to next TextFormField.
class _MyAppState extends State {

  final white = Colors.white;
  final _passwordFocusNode = FocusNode();
  bool hidePassword = true;
  final _formKey = GlobalKey();


  final outlineInputBorder = OutlineInputBorder(
    borderRadius: BorderRadius.all(
      Radius.circular(10.0),
    ),
    borderSide: BorderSide(color: Colors.white),
  );


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Center(
          child: Container(
            constraints: BoxConstraints.expand(),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/subway.jpg'),
                fit: BoxFit.cover,
              ),
            ),
            child: SingleChildScrollView(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        SizedBox(
                          height: 150,
                        ),
                        Text(
                          'ANDROIDRIDE',
                          style: TextStyle(
                            fontSize: 36,
                            color: white,
                          ),
                          textAlign: TextAlign.center,
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        TextFormField(
                          autofocus: true,//autofocus enabled.
                          onSaved: (newValue) 
                          {
                            //prints value when _formKey.currentState.save();
                            print("Username: $newValue");
                          },
                          validator: (value)//provides value in TextFormField
                          {
                            if (value.isEmpty) 
                            {//TextFormField is empty, show below text
                              return 'Please type your username';
                            }
                            //return null means successful validation.
                            return null;
                          },
                          onFieldSubmitted: (_) 
                          {//change Focus to next TextFormField (here password TextFormField)
                            FocusScope.of(context)
                                .requestFocus(_passwordFocusNode);
                          },
                          //soft keyboard shows next icon in bottom right corner
                          textInputAction: TextInputAction.next,
                          style: TextStyle(
                            color: white,
                          ),
                          maxLines: 1,
                          decoration: InputDecoration(
                            hintText: 'Username',
                            focusedBorder: outlineInputBorder,
                            border: outlineInputBorder,
                            hintStyle: TextStyle(
                              color: white,
                            ),
                            prefixIcon: const Icon(
                              Icons.account_circle_outlined,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                        SizedBox(
                          height: 15,
                        ),
                        TextFormField(
                          maxLines: 1,
                          obscureText: hidePassword,//true hides password, false shows.
                          focusNode: _passwordFocusNode,
                          onSaved: (newValue) 
                          { //print value when _formKey.currentState.save() calls.
                            print("Password: $newValue");
                          },
                          validator: (value) 
                          {
                            //validates when _formKey.currentState.validate() calls.
                            if (value.isEmpty) {
                              return 'Enter your password';
                            }
                            if (value.length < 4) {
                              return 'password must be at least 4 characters';
                            }
                            return null;
                          },
                          style: TextStyle(
                            color: white,
                          ),
                          decoration: InputDecoration(
                            hintText: 'Password',
                            focusedBorder: outlineInputBorder,
                            border: outlineInputBorder,
                            hintStyle: TextStyle(
                              color: white,
                            ),
                            prefixIcon: const Icon(
                              Icons.lock_open_outlined,
                              color: Colors.white54,
                            ),
                            suffixIcon: IconButton(
                              onPressed: () {
                                setState(() 
                                {
                                  hidePassword = !hidePassword;
                                });
                              },
                              icon: Icon(
                                hidePassword
                                    ? Icons.visibility
                                    : Icons.visibility_off,
                                color: Colors.white70,
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: ElevatedButton(
                            style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.all(
                                  Colors.white24),
                            ),
                            onPressed: () {
                              //calls _printFormValues() method
                              _printFormValues();
                            },
                            child: Text('LOGIN'),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


  • When both TextFields submitted and ElevatedButton tapped, it calls _printFormValues() method.
  • _formKey.currentState.validate() calls, it internally calls validator in TextFormFields, validates and returns true if there are no errors.
  • Otherwise shows text message which specified in validator.
  • _formKey.currentState.save() internally calls onSaved when there are no validation errors.
  • resizeToAvoidBottomInset: false, prevents resizing body.
  • Don’t forget to dispose the FocusNode.
  void _printFormValues() {
    final _isTrue = _formKey.currentState.validate();

    if (!_isTrue) {
      return;
    }
    _formKey.currentState.save();
  }

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


flutter login page output

That’s all for now. Thank you.

More Information : Container Docs

2 Flutter Path Provider Examples With Tutorial

flutter path provider example
In this post, you will learn about the Flutter path provider package.

Okay, what it actually does?

Using path_provider package, you can easily find the most used locations on the filesystem of the device. It supports both iOS and Android.

Path provider methods – getApplicationDocumentDirectory() to latest ones

You can use these 8 methods to access device storage.

  1. getApplicationDocumentsDirectory(): Gives path to the directory where Application can place it’s private files, Files only get wiped out when application itself removed.
    iOSNSDocumentsDirectory API.
    Android – returns AppData directory.
  2. 
    
      final directory = await getApplicationDocumentsDirectory();
    
    
    

  3. getTemporaryDirectory(): This gives path to the temporary directory in device. Files can be deleted at any time.
    iOS – It uses NSCachesDirectory API
    Android – Use getCacheDir API
  4. getExternalStorageDirectories: It returns list of path of directories where app’s specific data can be stored. Commonly, path lives in external storage partitions or SD cards. Now it’s only available in Android, So before use, it’s better to find out the operating system. on iOS, it shows UnSupportedError.
    Android: it returns Context.getExternalFilesDirs(String type).
    Below API 19: Context.getExternalFilesDir(String type).
  5. getExternalStorageDirectory(): Only available in Android. Provides path to External storage(Generally SD card).

    This does not support in iOS, it will throw UnSupportedError if you use it.

  6. getDownloadsDirectory(): It returns path of the directory where downloaded files get stored. Not available in Android and iOS, it gives UnSupportedError.
  7. getExternalCacheDirectories(): It returns list of path of directories where app’s external cache data get stored. Commonly, these types of paths lives in SD cards and only available in Android, better check it out which OS is running because iOS throws UnSupportedError.

    Android – returns Context.getExternalCacheDirs().
    Below API 19 : Context.getExternalCacheDir() API.

  8. getLibraryDirectory():It returns path of the directory where app store persistent data such as sqlite.db, Not available in Android.
  9. getApplicationSupportDirectory(): It returns the directory where app place support files. It’s not recommended to use for user data files.

    iOS – Uses NSApplicationSupportDirectory API.
    Android – Uses getFilesDir API.

Let’s make a simple Create and Read File example, that will help you to learn about it better.

Flutter Path Provider Example – Create File and Read

path_provider example - Create File
In this example, you will learn how to create a text file, input from TextField using path provider and print to Text widget.

So let’s create a Flutter project named flutter_path_provider_example.


dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.0
  path_provider: ^1.6.24

  • Open the project and pubspec.yaml, put path_provider package.


import 'package:flutter/material.dart';

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

class PathProviderExample extends StatefulWidget {
  @override
  _PathProviderExampleState createState() => _PathProviderExampleState();
}

class _PathProviderExampleState extends State {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

  • type stful for StatefulWidget and provide name – PathProviderExample


   final textController = TextEditingController();
   String text;


  • Create textController instance to access input from TextField.
  • text variable for storing text from TextField.
  • Put both of them in the State class.


@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Path Provider Example',
    home: Scaffold(
      appBar: AppBar(
        title: Text('Flutter Path Provider Example'),
      ),
      body: Column(
        children: [
          Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 18.0, vertical: 10),
            child: TextField(
              textAlign: TextAlign.center,//input aligns to center
              controller: textController,//assigns TextEditingController
            ),
          ),
          SizedBox(
            height: 10,
          ),
          ElevatedButton(
            child: Text('Create File'),
            onPressed: () => createFile(textController.text),//calls createFile() when //button pressed
          ),
          ElevatedButton(
            onPressed: () async {
              await readFile();//calls readFile()
              setState(() {});//rebuilds the UI.
            },
            child: Text('Read File'),
          ),
          SizedBox(
            height: 20,
          ),
          if (text != null) Text('$text')//text set if it's not null.
        ],
      ),
    ),
  );
}

  • Using Scaffold, simply make structure of the app.
  • Column arranges widget in vertical order.
  • Padding widget provides empty space around the TextField.
  • SizedBox gives some space between Widgets.
  • ElevatedButton is latest button provided by Flutter. (RaisedButton – obsolete now).

Let’s create createFile() method now.


Future createFile(String text) async {
//provides directory path.
    final directory = await getApplicationDocumentsDirectory();
//creates text_file in the provided path.
    final file = File('${directory.path}/text_file.txt');
    await file.writeAsString(text);
  }

  • import below statements to avoid red squiqqly lines:
    • import ‘dart:io’; – importing File class and methods.
    • import ‘package:path_provider/path_provider.dart’; – getApplicationDocumentsDirectory()
  • This is an asynchrononus method, so we need to use await and async keyword.
  • Input from the TextField is written to the text file.

just like createFile, make readFile() method.


Future readFile() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/text_file.txt');
      text = await file.readAsString();
    } catch (e) {
      print('exception');
    }
  }

  • text_file is read using readAsString() method.

Don’t forget to dispose TextEditingController.


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


Where files get stored when using getApplicationDocumentsDirectory() in Flutter?

Let’s check it out where is text_file get stored that we created in above example.

device file explorer android studio

Using Android Studio, View -> Tool Windows -> Device File Explorer.

text file location in path provider

Go for this location /data/data/com.androidride.flutter_path_provider_example/app_flutter/text_file.txt

Flutter Create Directory Example

flutter create directory example - path provider

In this flutter path provider example, you will learn how to create a directory using Path Provider package.

Just like the First Example, create a Flutter project and put path_provider pacakage in pubspec.yaml.

open main.dart and clear everything and type stless for StatelessWidget.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget 
{
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}


Before creating UI, let’s create createDir() method which creates directory.



  createDir() async {
    final directoryName = 'AndroidRide';
    final docDir = await getApplicationDocumentsDirectory();
    final myDir = Directory('${docDir.path}/$directoryName');

    if (await myDir.exists()) {
      print(myDir.path);
    }

    final dir = await myDir.create(recursive: true);
    print(dir.path);
  }

  • Import these:
    • import ‘dart:io’;

    • import ‘package:path_provider/path_provider.dart’;

Let’s complete the UI.


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Create New Directory Example'),
        ),
        body: Container(
          padding: EdgeInsets.all(20.0),
          alignment: Alignment.topCenter,
          child: ElevatedButton(
            child: Text('Create Directory'),
            onPressed: () {
              createDir();
            },
          ),
        ),
      ),
    );
  }



The directory gets created when you tap on the “Create Directory” Button. Check it out the directory using Device File Explorer.

flutter create new directory example - path provider

That’s all for now.

More Information: path_provider

Please disable your adblocker or whitelist this site!