Author

admin

Browsing

Render List Of Row Or ListView Inside Column in Flutter

In this post, you will learn how to render list of rows or listview inside Column. while implementing ListView inside Column, you may get errors. Using below examples, you can understand how to avoid them.

Let’s start.

In this first example, I will implement list of row texts inside Column.

List of Row Inside A Column Example – I

list of row inside column in flutter

  • I have used a For loop to generate Row’s childrens.
  • The for loop creates 50 rows inside the Column, if it exceeds the screen height. You will get the renderflex errors.
  • To avoid yellow & black renderflex overflow errors, You can use ListView or SingleChildScrollView around the Column.
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: 'List of Row Inside A Column',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('List of Row Inside A Column'),
        ),
        body: 
        // SingleChildScrollView(
        //   child: 
          Column(
            children: [
              for (int i = 1; i <= 50; i++)
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'text $i',
                      style: const TextStyle(
                        fontSize: 18,
                      ),
                    ),
                    const SizedBox(
                      width: 20,
                    ),
                    Text(
                      'content $i',
                      style: const TextStyle(
                        fontSize: 18,
                      ),
                    ),
                  ],
                ),
            ],
          ),
        //),
      ),
    );
  }
}

List of Row Inside a Column in Flutter - II

flutter render list of row inside column
This example is really useful for those who are making form inside a column. Here, I have used a TextField inside Row.

If you are making any login or signin form, recommended to use Form and TextFormField.

  • You must aware that TextField or TextFormField inside a Row can create InputDecorator unbound width error. This is due to TextFormField does not have intrinsic width (natural width), and row wants it's childs intrinsic size and that's makes the problem
  • So either Use Expanded, Flexible or SizedBox with width property around the TextField or TextFormField.
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: 'List of Row Inside A Column',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('List of Row Inside A Column'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              for (int i = 1; i <= 50; i++)
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [
                    SizedBox(width: 10),
                    Text('Name : '),
                    SizedBox(width: 10),
                    Flexible(
                      child: TextField(
                        decoration: InputDecoration(hintText: 'name'),
                      ),
                    )
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}


How to use ListView inside Column In Flutter?

When you place ListView inside column, it ends with an exception most of the time. because both ListView and Column tries to expand in the main axis direction (here I am talking above Vertical direction). Flutter needs to know how much space ListView and Column needed.

Using Expanded

listview inside column using expanded

  • Use Expanded widget around the ListView - Recommended.
  • It expands the listview to take the available space inside the column.
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('ListView Inside Column Using Expanded'),
        ),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: const Text(
                'ListView Inside Column Using Expanded',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ),
            Expanded(
              child: ListView(
                padding: EdgeInsets.all(8),
                children: [
                  for (int i = 0; i < 50; i++)
                    Align(
                      alignment: Alignment.center,
                      child: Text('Item $i'),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}


Using shrinkWrap property

flutter render list of row inside column

  • By setting, shrinkWrap:true, ListView will take as much as space only the children needed.
  • Actually, it will compute the size of the entire content in ListView.
  • But setting shrinkWrap:true can make performance hit. So avoid it as much as you can.
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('ListView Inside Column Using shrinkWrap Property'),
        ),
        body: Column(
          children: [
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                'ListView Inside Column Using shrinkWrap Property',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ),
            ListView(
              shrinkWrap: true,
              padding: EdgeInsets.all(8),
              children: [
                for (int i = 0; i < 30; i++)
                  Align(
                    alignment: Alignment.center,
                    child: Text('Item $i'),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Using SizedBox

flutter render list of row inside column

  • Use SizedBox around the ListView with a specific height value.
  • Height of the listview turns to SizedBox height.
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('ListView Inside Column Using SizedBox'),
        ),
        body: Column(
          children: [
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                'ListView Inside Column Using SizedBox',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ),
            SizedBox(
              height: 500,
              child: ListView(
                padding: EdgeInsets.all(8),
                children: [
                  for (int i = 0; i < 50; i++)
                    Align(
                      alignment: Alignment.center,
                      child: Text('Item $i'),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}



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

3 Ways To Change Elevated Button Color In Flutter

Do you want to change color of Elevated Button?

Then you are in the right place.

So let’s start with a simple example.

Most of the time, this is the one you really needed.

How To Change Elevated Button Color?

change elevatedbutton color

  • Use style property of ElevatedButton and pass ElevatedButton.styleFrom().
  • Inside, ElevatedButton.styleFrom(), give primary parameter and color as value.
  • You can use onPrimary property to change Text Color of ElevatedButton.

ElevatedButton(
                  child: const Text('ElevatedButton'),
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    primary: Colors.deepOrangeAccent,
                    //onPrimary: Colors.black,
                  ),
                ),

How To Change Elevated Button Color Using Theme?

elevated button color change using theme widget
Sometimes you need to set same color and text color for a group of ElevatedButtons used in a form or section. You don’t need to use style property for each one. In these situations, You can use Theme widget.

  • This example, I have used Column for holding two ElevatedButton and the Column is wrapped with Theme Widget.
  • Theme widget provides elevatedButtonTheme property to set our style.
  • You need to specify with ElevatedButtonThemeData object and style values.
  • It affects all the children inside of it.

Theme(
                  data: ThemeData(
                    elevatedButtonTheme: ElevatedButtonThemeData(
                      style: ElevatedButton.styleFrom(
                        onPrimary: Colors.white,
                        primary: Colors.green,
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      ElevatedButton(
                        child: const Text('ElevatedButton 1'),
                        onPressed: () {},
                      ),
                     const SizedBox(
                        height: 10,
                      ),
                      ElevatedButton(
                        child: const Text('ElevatedButton 2'),
                        onPressed: () {},
                      ),
                    ],
                  ),
                )

How To Change Elevated Button Color Using Theme – App level

  • Using this MaterialApp theme property, you can change all ElevatedButton color in your app with simple piece of code.
  • You should give ThemeData object and elevatedButtonTheme property value should be ElevatedButtonThemeData

return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ElevatedButton Color Change Example',
      theme: ThemeData(
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            primary: Colors.red,
          ),
        ),
      ),

Complete Source Code

elevated button color flutter

  • In this, main example, I have used 3 different ways mentioned above in this post.
  • First example uses the color given by App theme data. So it chooses, Red color.
  • Second, ElevatedButton overrides app level theme color by using its own style. So here, ElevatedButton uses Orange color and also black for text color.
  • Third one, we have used Theme Widget, using that you can change color of all the children (ElevatedButton)inside of Theme Widget.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ElevatedButton Color Change Example',
      theme: ThemeData(
        //primarySwatch: Colors.red,
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            primary: Colors.red,
          ),
        ),
      ),
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Flutter ElevatedButton Color Change Example'),
          ),
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
        //It uses applevel theme color
        ElevatedButton(
                  child: const Text('ElevatedButton'),
                  onPressed: () {},
                ),
//Here It uses own style color by overriding app level color.
                ElevatedButton(
                  child: const Text('ElevatedButton'),
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    primary: Colors.deepOrangeAccent,
                    onPrimary: Colors.black,
                  ),
                ),
//Here, Theme provides color for the ElevatedButton.
                Theme(
                  data: ThemeData(
                    elevatedButtonTheme: ElevatedButtonThemeData(
                      style: ElevatedButton.styleFrom(
                        primary: Colors.green,
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      ElevatedButton(
                        child: const Text('ElevatedButton 1'),
                        onPressed: () {},
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      ElevatedButton(
                        child: const Text('ElevatedButton 2'),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

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

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,
            ),
          ],
        ),
      ),
    );
  }
}


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

Flutter Animated Icon Example With Tutorial

Hi, Welcome to AndroidRide.

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

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

How To Use AnimatedIcon In Flutter project?


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

AnimatedIcon needs 2 things.

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

AnimatedIcon Example In Simple Steps

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

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

Flutter AnimatedIcon Example

Create a Flutter project – check this tutorial.

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

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

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

import 'package:flutter/material.dart';

void main() => const AnimatedIconExample();

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

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

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


Next we need to create an AnimationController.

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


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


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

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


Let’s create a variable for changing animation state.

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

bool isAnimating = false;

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

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

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

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

Check out the complete source code.


import 'package:flutter/material.dart';

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

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

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

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

  bool isAnimating = false;

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

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

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

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

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



flutter animated icon example

Flutter AnimatedIcon List

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

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

AnimatedIcon Properties

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

Download Source Code

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

5 Flutter Bottom Button Examples With Tutorial

Hi guys, Welcome to AndroidRide.

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

okay… Let’s start.

1. Flutter Bottom Button Using FloatingActionButton

Let’s start with FloatingActionButton.

bottom button fab

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

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

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

2. Bottom Button Using FloatingActionButton.extended()

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

Yes, FloatingActionButtonLocation.centerFloat


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

3. Flutter Bottom Button Using BottomNavigationBar

flutter bottom button

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

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

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


4. Bottom Button Using BottomNavigationBar – Two Items

flutter bottom button using bottomnavigationbar

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

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

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

5. Bottom Button Using Stack and Align

flutter bottom button

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

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

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

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

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

2 Ways To Make Clickable Container in Flutter: 3 Examples

Do you want to make a clickable container in Flutter?

Then this post is definitely for you.

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

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

Let’s start with GestureDetector.

1. How To Make A Clickable Container Using GestureDetector?

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

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

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

    2. How To Make Clickable Container Using InkWell?

    clickable container using inkwell

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

    • Wrap the container with Inkwell and create onTap property.

    that’s it. everything done.

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

    3. Create a Clickable AnimatedContainer

    clickable animated container

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

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

    Create a project with all the above examples.

    clickable container flutter

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

    Run the application.

    Download Source Code

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

Please disable your adblocker or whitelist this site!