Author

admin

Browsing

Flutter Elevated Button With Rounded Corners – 5 Examples

Buttons have huge importance in every UI and using the same old fashioned rectangle shape button can be less attractive.

So In this post, you will make Elevated Button with rounded corners. It’s actually easy, but we can use different ways to make it happen.

ElevatedButton available since Flutter 1.22, it’s a replacement for old RaisedButton.

So without wasting time, let’s get started.

Flutter ElevatedButton With Rounded Corners

flutter elevated button rounded

Let’s start with a simple one. we will change the style of ElevatedButton using style property.

  • We can use ElevatedButton.styleFrom() and provide RoundedRectangleBorder as shape property value.
  • BorderRadius.circular(value) creates rounded corner in each side.

ElevatedButton(
                onPressed: () {},
                child: const Text('Rounded Elevated Button'),
                style: ElevatedButton.styleFrom(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),

ElevatedButton With Rounded Corners – StadiumBorder shape

flutter elevated button rounded

I am already discussed about StadiumBorder in detail.

  • Using StadiumBorder, we can easily make stadium shaped Button.
  • Inside ElevatedButton.styleFrom(), Use shape property and give StadiumBorder() as value.
  • That’s enough, you can change color using primary property.
ElevatedButton(
                onPressed: () {},
                child: const Text('Elevated Button - Stadium Border Shape'),
                style: ElevatedButton.styleFrom(
                  primary: Colors.red,
                  shape: StadiumBorder(),
                ),
              ),

Rounded ElevatedButton With Container

flutter elevated button with rounded corners

  • In this example, I have increased ElevatedButton width using Container
  • You can also increase or decrease height using height property.

Container(
                width: 350,
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('Elevated Button'),
                  style: ElevatedButton.styleFrom(
                    primary: Colors.red,
                    shape: const StadiumBorder(),
                  ),
                ),
              ),

Flutter ElevatedButton.icon With Rounded Corner

flutter elevated button rounded corners
Here, we can make a rounded Elevatedbutton with icon. Just use ElevatedButton.icon() with your needed icon.


ElevatedButton.icon(
                onPressed: () {},
                icon: const Icon(Icons.access_alarm_rounded),
                label: const Text("Alarm"),
                style: ElevatedButton.styleFrom(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),

ElevatedButton.icon with Container

elevatedbutton.icon with container

Just like above example, we will use ElevatedButton.icon with Container just for additional width.


Container(
                width: 350,
                child: ElevatedButton.icon(
                  icon: Icon(Icons.alarm),
                  onPressed: () {},
                  label: const Text('Elevated Button'),
                  style: ElevatedButton.styleFrom(
                    primary: Colors.red,
                    shape: const StadiumBorder(),
                  ),
                ),
              ),

Using ClipRRect For Rounded Corners

cliprrect elevatedbutton

As a final one, you can use ClipRRect with ElevatedButton. It gets rounded rectangle around the elevatedbutton.


ClipRRect(
                borderRadius: BorderRadius.circular(15),
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('elevated button'),
                ),
              ),

ClipRRect with ElevatedButton.icon

cliprrect with elevatedbutton.icon

based on the above demo, ElevatedButton.icon will covered with rounded rectangle.

ClipRRect(
                borderRadius: BorderRadius.circular(15),
                child: ElevatedButton.icon(
                  icon: Icon(Icons.alarm),
                  onPressed: () {},
                  label: Text('elevated button'),
                ),
              ),

Complete source code is given below.
flutter elevated button rounded


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ElevatedButton With Rounded Corners'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {},
                child: const Text('Rounded Elevated Button'),
                style: ElevatedButton.styleFrom(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              //stadiumborder
              ElevatedButton(
                onPressed: () {},
                child: const Text('Elevated Button - Stadium Border Shape'),
                style: ElevatedButton.styleFrom(
                  primary: Colors.red,
                  shape: const StadiumBorder(),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              //stadiumborder with container
              Container(
                width: 350,
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('Elevated Button'),
                  style: ElevatedButton.styleFrom(
                    primary: Colors.red,
                    shape: const StadiumBorder(),
                  ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              //rounded elevatedbutton with icon
              ElevatedButton.icon(
                onPressed: () {},
                icon: const Icon(Icons.access_alarm_rounded),
                label: const Text("Alarm"),
                style: ElevatedButton.styleFrom(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              //stadium border with container + elevated icon
              Container(
                width: 350,
                child: ElevatedButton.icon(
                  icon: Icon(Icons.alarm),
                  onPressed: () {},
                  label: const Text('Elevated Button'),
                  style: ElevatedButton.styleFrom(
                    primary: Colors.red,
                    shape: const StadiumBorder(),
                  ),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              //cliprrect with elevatedbutton
              ClipRRect(
                borderRadius: BorderRadius.circular(35),
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('elevated button'),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              //cliprrect with elevatedbutton.icon
              ClipRRect(
                borderRadius: BorderRadius.circular(35),
                child: ElevatedButton.icon(
                  icon: Icon(Icons.alarm),
                  onPressed: () {},
                  label: Text('elevated button'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


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

StadiumBorder
Flutter ElevatedButton Docs

Flutter Container Background Color(+Gradient)- 3 Examples

Hi, Welcome to AndroidRide.

In this post, you will learn how to set background color of the Container.
without wasting time, let’s start.

Flutter Container Background Color – Using color property

flutter background color container
By default, Container comes with a color property. Not only property, Flutter also provides lots of default colors to make our UI better.

  • Here, I have used Colors.blue. You can use any other colors.
  • Check it out other colors provided by Colors class.
Container(
                  width: 200,
                  height: 80,
                  color: Colors.red,
                  child: const Center(
                    child: Text(
                      'color property',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),

Container Background color with Hex Code

  • If you want to use any of the color code you like. For example, you got #FA8072 on the web. Just remove # and replace it with 0xff
  • so #FA8072 becomes 0xffFA8072
  • Now pass it to Color class -> Color(0xffFA8072)

Container(
                  width: 200,
                  height: 80,
                  color: const Color(0xffFA8072),
                  child: const Center(
                    child: Text(
                      'Hex color code',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),

Background Color With Opacity


Sometimes, you don’t need fully opaque color for your container, so you can use opacity with colors to reduce the opaqueness.

  • By default, Colors class provides colors like White70, black54.
  • The number after the color name is opacity.
  • Here, white70 means white color with 70% opacity.

Container(
                  width: 200,
                  height: 80,
                  //color: Colors.red.withOpacity(0.5),
                  color: Colors.black54,
                  child: const Center(
                    child: Text(
                      'color with opacity',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),

  • Or you can use withOpacity() method with the value.
  • Just like given below.

Container(
                  width: 200,
                  height: 80,
                  color: Colors.red.withOpacity(0.5),
                  child: const Center(
                    child: Text(
                      'color with opacity',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),



Background Color Using BoxDecoration


Container’s decoration property can be used to set Background color. BoxDecoration also provides color property.

Container(
                  width: 200,
                  height: 80,
                  decoration: const BoxDecoration(
                    color: Colors.yellow,
                  ),
                  child: const Center(
                    child: Text(
                      'decoration property',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),

Container Background Color as Gradient

flutter container background color gradient

You can set gradient color as Container background. By using gradient, we can give our container a different look.

  • So we can use BoxDecoration and it’s gradient property to make background color.
  • Let’s give starting and ending color in an array as value of colors property.
  • Container(
                      width: 200,
                      height: 80,
                      decoration: const BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            Color(0xFF0061ff),
                            Color(0xFF60efff),
                          ],
                        ),
                      ),
                      child: const Center(
                        child: Text(
                          'Gradient color',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),

    Complete Source code

    flutter container background color

    • Here, I included all containers told above with SizedBox.
    • You can also use Padding widget or You can use Container margin property for extra free space.
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Container Background Color Example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: ContainerBackgroundColorEx(),
        );
      }
    }
    
    class ContainerBackgroundColorEx extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
            appBar: AppBar(
              title: Text('Container Background Color Example'),
            ),
            body: Center(
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      width: 200,
                      height: 80,
                      color: Colors.red,
                      child: const Center(
                        child: Text(
                          'color property',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.01,
                    ),
                    Container(
                      width: 200,
                      height: 80,
                      color: const Color(0xffFA8072),
                      child: const Center(
                        child: Text(
                          'Hex color code',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.01,
                    ),
                    Container(
                      width: 200,
                      height: 80,
                      //color: Colors.red.withOpacity(0.5),
                      color: Colors.black54,
                      child: const Center(
                        child: Text(
                          'color with opacity',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.01,
                    ),
                    Container(
                      width: 200,
                      height: 80,
                      decoration: const BoxDecoration(
                        color: Colors.yellow,
                      ),
                      child: const Center(
                        child: Text(
                          'decoration property',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.01,
                    ),
                    Container(
                      width: 200,
                      height: 80,
                      decoration: const BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            Color(0xFF0061ff),
                            Color(0xFF60efff),
                          ],
                        ),
                      ),
                      child: const Center(
                        child: Text(
                          'Gradient color',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.01,
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
    
    

    okay, that’s all for now.

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

5 Ways – Flutter Row Background Color Examples

In this post, you will learn how to set background color of Row in Flutter.

Row does not have any default attribute to set background color.

So what we do then?

Just wrap Row with other widgets, give color to them and it will affect in Row’s background.

Wraping a widget with other widget is very common in Flutter :-).

so let’s start.

If you don’t know how to setup Flutter and create project – use this link

1. Flutter Row Background Color Using Container

  • Container used for painting and positioning widgets.
  • Use color property to set color. This will be Row‘s background color. If we wrap the Row widget.
  • Colors.blue a constant value which gives blue color.

          Container(
            color: Colors.blue,
            padding: const EdgeInsets.all(8.0),
            margin: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: const [
                Text(
                  'Example 1',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                ),
                SizedBox(
                  width: 5,
                ),
                Text(
                  'Text 1',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                )
              ],
            ),
          ),


2. Using Container Decoration Property

  • Container decoration property can be used to set background color and also decorate the borders.
  • Just like above example, just use it as parent of Row widget.
  • By the way you can not use both color and BoxDecoration color property, it leads you to get error – Because color is a shorthand for BoxDecoration color.

Container(
            decoration: const BoxDecoration(
              color: Colors.pinkAccent,
              borderRadius: BorderRadius.all(
                Radius.circular(8),
              ),
            ),
            height: 100,
            width: double.infinity,
            margin: const EdgeInsets.all(15),
            padding: const EdgeInsets.all(15),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const [
                Text(
                  'Example 2',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(
                  width: 5,
                ),
                Text(
                  'Text 2',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),

3. Using Ink

  • We can use Ink widget to draw decorations on Material widgets.
  • Here, you can use Ink class color property to set color.
  • That’s all.

 Ink(
            color: Colors.brown,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: const [
                Text(
                  'Example 3',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                  ),
                ),
                Text(
                  'Text 3',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                  ),
                ),
              ],
            ),
          ),

4. Using ColoredBox

  • Just like Container, you can use ColoredBox to set background Color.
  • It fills the color using color property and draw the child widget over it.

ColoredBox(
            color: Colors.red,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: const [
                Text(
                  'Example 4',
                  style: TextStyle(color: Colors.white, fontSize: 24),
                ),
                SizedBox(
                  width: 10,
                ),
                Text(
                  'Text 4',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                  ),
                ),
              ],
            ),
          ),

Using DecoratedBox

flutter row background color

  • DecoratedBox is a lighter widget when compared to Container.

SizedBox(
            width: double.infinity,
            height: 100,
            child: DecoratedBox(
              decoration: const BoxDecoration(
                color: Colors.purple,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  Expanded(
                    child: Text(
                      'Example 5',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  Expanded(
                    child: Text(
                      'Text 5',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ],
              ),
            ),
          ),

Create a complete project with above examples.

Complete Source Code

flutter row background color

  • You can use SizedBox for making empty spaces or use Flutter Padding Widget
    • 
      import 'package:flutter/material.dart';
      
      void main() {
        runApp(const MyApp());
      }
      
      class MyApp extends StatelessWidget {
        const MyApp({Key? key}) : super(key: key);
      
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: MyPage(),
          );
        }
      }
      
      class MyPage extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: Text('Futter Row Background Color'),
            ),
            body: Column(
              children: [
                SizedBox(
                  height: 10,
                ),
                Container(
                  color: Colors.blue,
                  padding: const EdgeInsets.all(8.0),
                  margin: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: const [
                      Text(
                        'Example 1',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                        ),
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      Text(
                        'Text 1',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                        ),
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Container(
                  decoration: const BoxDecoration(
                    color: Colors.pinkAccent,
                    borderRadius: BorderRadius.all(
                      Radius.circular(8),
                    ),
                  ),
                  height: 100,
                  width: double.infinity,
                  margin: const EdgeInsets.all(15),
                  padding: const EdgeInsets.all(15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: const [
                      Text(
                        'Example 2',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      Text(
                        'Text 2',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Ink(
                  color: Colors.brown,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: const [
                      Text(
                        'Example 3',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                        ),
                      ),
                      Text(
                        'Text 3',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 25,
                ),
                ColoredBox(
                  color: Colors.red,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: const [
                      Text(
                        'Example 4',
                        style: TextStyle(color: Colors.white, fontSize: 24),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        'Text 4',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 25,
                ),
                SizedBox(
                  width: double.infinity,
                  height: 100,
                  child: DecoratedBox(
                    decoration: const BoxDecoration(
                      color: Colors.purple,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: const [
                        Expanded(
                          child: Text(
                            'Example 5',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 24,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        Expanded(
                          child: Text(
                            'Text 5',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 24,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        }
      }
      
      
      

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

4 Ways To Generate Random Number In Flutter

Hi, Welcome to AndroidRide.

Random numbers have a big role in our daily life. But we really don’t think that much about that.
They are used in computer encryption, gambling, and lotteries and many more.

So today, you will learn how to generate random number in dart using a Flutter app.

Let’s start…

  • First of all, we will use Random class from dart:math. So import it that first

import 'dart:math';

Let’s create a project.

1. How To Generate Random Number using Random?

 
 

  Random random = Random();

 _randomNumber1 = random.nextInt(50);

  • In this example, _randomNumber1 value will between 0 to 4950 will not be included.
  • You need to provide the maximum value. Then it will generate values between 0 and the maximum value.

2. Generate random number using random.secure

 
Random random2 = Random.secure();

_randomNumber2 = random2.nextInt(50);

  • Using Random.secure(), we can create cryptographically generated random number.
  • It also generates random number between 0 to 49, if it fails an Unsupportederror will thrown.

3. Random double value using random.nextDouble


Random random = Random();
_randomNumber3 = random.nextDouble() * 50;

  • In this example, we will generate double values, it will not include 50.0000

4. Generate random number in range

var min = 1;
var max = 6;

_randomNumber4 = min + random.nextInt(max - min);

  • If you want to generate random number in range, use this technique.
  • In this example, it generates values – 1 to 5.
  • it will not generate 6.

flutter random number
Let’s create a final example which uses all above ways, here I have added 4 buttons to execute each methods.

When you click on it, everyone in them will generate random number and show it in Text.

Full Source Code


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

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

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextStyle style = const TextStyle(
    fontSize: 25,
    fontWeight: FontWeight.bold,
  );

  int _randomNumber1 = 0;
  int _randomNumber2 = 0;
  double _randomNumber3 = 0.0;
  int _randomNumber4 = 0;

  Random random = Random();
  Random random2 = Random.secure();

  void _generateRandomNumber1() {
    setState(() {
      _randomNumber1 = random.nextInt(50);
    });
  }

  void _generateRandomNumber2() {
    setState(() {
      _randomNumber2 = random2.nextInt(50);
    });
  }

  void _generateRandomNumber3() {
    setState(() {
      _randomNumber3 = random.nextDouble() * 50;
    });
  }

  void _generateRandomNumberInRange() {
    var min = 1;
    var max = 6;

    setState(() {
      _randomNumber4 = min + random.nextInt(max - min);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Random number generator'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '$_randomNumber1',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumber1,
                child: const Text('Generate Random number - 1'),
              ),
              const SizedBox(
                height: 10,
              ),
              Text(
                '$_randomNumber2',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumber2,
                child: const Text('Generate Random number - 2'),
              ),
              const SizedBox(
                height: 15,
              ),
              Text(
                '$_randomNumber3',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumber3,
                child: const Text('Generate Random number - 3'),
              ),
              Text(
                '$_randomNumber4',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumberInRange,
                child: const Text('Generate Random number - 4'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

2 Flutter Folder Picker Examples with Tutorial

Hi, Welcome to AndroidRide.

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

okay..Let’s start then.

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

How To Pick Folder Using easy_folder_picker package – Only Android.

flutter folder picker using easy_folder_picker

You can also use Flutter command to create project.

I am using Flutter 2.5.1
Dart: 2.12.0

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


  easy_folder_picker: ^1.1.1

flutter folderpicker permissions

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


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

//if you want to create folders by users

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

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

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


android {
  compileSdkVersion 31

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

 Directory? selectedDirectory;

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

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

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


Here we go, the complete code is here.

Complete Source Code


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

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

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

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

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

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

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

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

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

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


Flutter folder Picker Using filesystem_picker package

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


filesystem_picker: ^2.0.0
permission_handler: ^8.2.5

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


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

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

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

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

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


Full Source Code


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

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

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

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

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

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

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

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

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

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


[sociallocker id=”2232″]flutter folder picker source code [/sociallocker]

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

Flutter Animated Icon Example With Tutorial

Hi, Welcome to AndroidRide.

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

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

How To Use AnimatedIcon In Flutter project?


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

AnimatedIcon needs 2 things.

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

AnimatedIcon Example In Simple Steps

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

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

Flutter AnimatedIcon Example

Create a Flutter project – check this tutorial.

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

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

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

import 'package:flutter/material.dart';

void main() => const AnimatedIconExample();

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

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

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


Next we need to create an AnimationController.

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


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


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

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


Let’s create a variable for changing animation state.

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

bool isAnimating = false;

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

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

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

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

Check out the complete source code.


import 'package:flutter/material.dart';

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

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

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

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

  bool isAnimating = false;

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

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

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

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

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



flutter animated icon example

Flutter AnimatedIcon List

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

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

AnimatedIcon Properties

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

Download Source Code

[sociallocker id=2232]flutter_animated_icon_example[/sociallocker]

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

5 Flutter Bottom Button Examples With Tutorial

Hi guys, Welcome to AndroidRide.

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

okay… Let’s start.

1. Flutter Bottom Button Using FloatingActionButton

Let’s start with FloatingActionButton.

bottom button fab

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

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

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

2. Bottom Button Using FloatingActionButton.extended()

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

Yes, FloatingActionButtonLocation.centerFloat


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

3. Flutter Bottom Button Using BottomNavigationBar

flutter bottom button

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

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

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


4. Bottom Button Using BottomNavigationBar – Two Items

flutter bottom button using bottomnavigationbar

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

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

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

5. Bottom Button Using Stack and Align

flutter bottom button

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

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

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

Transparent Bottom AppBar With Buttons

tranparent bottom app bar with buttons

In this example, you will learn how to create tranparent appbar with IconButtons. First of all, you must add a background image in assets directory and define it in pubspec.yaml.

if you don’t know,how to do that? check this link.

  • Scaffold‘s extendBody: true – helps to show Scaffold’s body through bottom navigation bar’s notch.
  • color: Colors.transparent – it makes completely invisible bottom app bar.

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
//      extendBodyBehindAppBar: true,
      extendBody: true,
      body: Container(
        constraints: const BoxConstraints.expand(),
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(
              'assets/background.jpg',
            ),
            fit: BoxFit.cover,
          ),
        ),
        child: const Center(
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Text(
              'Transparent BottomAppBar With Buttons',
              style: TextStyle(
                backgroundColor: Colors.black,
                color: Colors.white,
                fontSize: 20,
              ),
            ),
          ),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        elevation: 0,
        color: Colors.transparent,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            IconButton(
              onPressed: () {
                print('button tapped');
              },
              icon: const Icon(
                Icons.menu,
                color: Colors.white,
              ),
            ),
            IconButton(
              onPressed: () {
                print('button tapped');
              },
              icon: const Icon(
                Icons.search,
                color: Colors.white,
              ),
            ),
            IconButton(
              onPressed: () {
                print('button tapped');
              },
              icon: const Icon(
                Icons.person,
                color: Colors.white,
              ),
            ),
            IconButton(
              onPressed: () {
                print('button tapped');
              },
              icon: const Icon(
                Icons.settings,
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Download Source Code

[sociallocker id=”2232″] flutter_bottom_button1[/sociallocker]

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

2 Ways To Make Clickable Container in Flutter: 3 Examples

Do you want to make a clickable container in Flutter?

Then this post is definitely for you.

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

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

Let’s start with GestureDetector.

1. How To Make A Clickable Container Using GestureDetector?

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

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

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

    2. How To Make Clickable Container Using InkWell?

    clickable container using inkwell

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

    • Wrap the container with Inkwell and create onTap property.

    that’s it. everything done.

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

    3. Create a Clickable AnimatedContainer

    clickable animated container

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

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

    Create a project with all the above examples.

    clickable container flutter

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

    Run the application.

    Download Source Code

    [sociallocker id=”2232″] clickable_container[/sociallocker]

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

4 Flutter ListView Navigation Examples With Tutorial

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

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

This post will definitely good for you.

1. ListView Navigation: Navigate To New Screen.

flutter listview navigation

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

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

Below is the code.

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

Full source code is given below.


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

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

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

class MyListView extends StatelessWidget {

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


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

Replace FirstScreen text whereever you see in SecondScreen and ThirdScreen.

You can also download the source code at the bottom.

first_screen.dart


import 'package:flutter/material.dart';

class FirstScreen extends StatelessWidget {


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

2. Flutter ListView Navigation + Passing Data

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

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

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

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

note.dart


class Note {
  final String title;
  final String content;

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


main.dart


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

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

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

class ListScreen extends StatelessWidget 
{

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

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


detail_screen.dart



import 'package:flutter/material.dart';

import 'note.dart';

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

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

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


3.ListView Navigation – Passing Data Through RouteSettings

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

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

Okay. How to get this data from DetailScreen?

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

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


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

note.dart


class Note {
  final String title;
  final String content;

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


main.dart


import 'package:flutter/material.dart';

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

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

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

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

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

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

detail_screen.dart


import 'package:flutter/material.dart';

import 'note.dart';

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

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



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

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

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

How to access this data in DetailScreen build method?

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

class DetailScreen extends StatefulWidget {
  final Note note;

  DetailScreen(this.note);

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

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


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

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

main.dart


import 'package:flutter/material.dart';

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

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

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

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

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

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


detail_screen.dart


import 'package:flutter/material.dart';

import 'note.dart';

class DetailScreen extends StatefulWidget {
  final Note note;

  DetailScreen(this.note);

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

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

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


Download Source Code

[sociallocker id=”2232″]
flutter listview navigation – source code
[/sociallocker]

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

Flutter TextField Password : 2 Examples

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

okay… Let’s start.

How To Make A Password Field In Flutter Using TextField?

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

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

Let’s create a simple example.

Flutter TextField & TextFormField – Password Field Example

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

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

Full source code is given below.



import 'package:flutter/material.dart';

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

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

class _MyAppState extends State<MyApp> {
  

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



How To Show/Hide Password With Visibility Icon

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

flutter textfield password icon animation

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

import 'package:flutter/material.dart';

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

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

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

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


flutter textfield password with eye icon

Flutter Login Page (Other Post)

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

So just check it out.

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

Please disable your adblocker or whitelist this site!