Home Blog Page 32

Flutter navigation Sidebar drawer – SidebarX package

0
Flutter SideBarX Navigation bar

Hi Guy’s, Welcome to Proto Coders Point. In this flutter tutorial let’s create a Sidebar Navigation Menu using a package i.e. Flutter SidebarX.

Flutter SidebarX

Let’s get started

In flutter there are two ways to create a navigation i.e. by tabs & Drawer. I found out a flutter package that is recently launched SideBarX using which flutter app developer can easily create multiplatform navigation drawer sidebar/ sidebar menu / side navigation drawer.

Sidebar Navigation menu is very useful for user for in-app navigation(page routing) or for user profile.

In this flutter tutorial Article let’s create a simple sidebar navigation menu by using flutter sidebarX package.

1. Create a new Flutter project or open any existing to implement sidebarX

I use Android Studio to build flutter application, you can use your favorite IDE.

create Project -> Android Studio -> File -> New -> New Flutter Project -> Give Project Name -> create project by click Finish.

2. Add/Install SidebarX package as dependencies

In your project structure look for file by name pubspec.yaml, Open it & under dependencies section add sidebarx package, as shown in below screenshot.

flutter sidebarx add dependecies  in pubspec.yaml file

click on pub get to download the package as external libraries.


3. Import SidebarX

Once the sidebarx dependencies is added into you flutter project as external libraries, To use it you need to import it.

import 'package:sidebarx/sidebarx.dart';

4. SidebarX Widget Properties

propertiesusage
controller :controller are used to give controller parent widget to listen to any event or chile state
theme : SidebarXTheme()Give a Theme to your sidebar navigator
extendedTheme:Can be used to increase the sidebar size usign SidebarX theme
footerDivider:Gives a Divider at the footer Diviter
headerBuilderSet a header at the top of sidebar, can be used to show profile image
items:[]List of SidebarXItem using which user can navigate between pages
extendIcon:show a icon to open the drawer/extend the sidebar
collapseIcon:Sidebar drawer closing icon

5. Sidebarx widget snippet code

1. For Mobile Devices – Small Screen

Scaffold(
      drawer: SidebarX(
        controller: SidebarXController(selectedIndex: 0, extended: true),
        items: const [
          SidebarXItem(icon: Icons.home, label: 'Home'),
          SidebarXItem(icon: Icons.search, label: 'Search'),
        ],
      ),
      body: const Center(child: Text('Your app body')),
)

2. For Browser or Platform app – Big Screen

Scaffold(
      body: Row(
        children: [
          SidebarX(
            controller: SidebarXController(selectedIndex: 0),
            items: const [
              SidebarXItem(icon: Icons.home, label: 'Home'),
              SidebarXItem(icon: Icons.search, label: 'Search'),
            ],
          ),
          // Your app screen body
        ],
      ),
   )

Complete Source Code – Flutter SidebarX example

Output Screenshot

flutter navigation bar example
flutter sidebarx example
sidebar menu item drawer

Source code main.dart

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

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryColor: primaryColor,
        canvasColor: canvasColor,
        scaffoldBackgroundColor: scaffoldBackgroundColor,
        textTheme: const TextTheme(
          headlineSmall: TextStyle(
            color: Colors.white,
            fontSize: 46,
            fontWeight: FontWeight.w800,
          ),
        ),
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}
const primaryColor = Color(0xFF6252DA);
const canvasColor = Color(0xFF2E2E48);
const scaffoldBackgroundColor = Color(0xFF7777B6);

class _MyHomePageState extends State<MyHomePage> {
  final _controller = SidebarXController(selectedIndex: 0, extended: true);
  final _key = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Builder(
        builder: (context) {
          final isSmallScreen = MediaQuery.of(context).size.width < 600;
          return Scaffold(
            key: _key,
            appBar: isSmallScreen ? AppBar(
              title: Text('SideBarX Example'),
              leading: IconButton(
                onPressed: (){
                  _key.currentState?.openDrawer();
                },
                icon: Icon(Icons.menu),
              ),
            ): null,
            drawer: SideBarXExample(controller: _controller,),
            body: Row(
              children: [
                if(!isSmallScreen) SideBarXExample(controller: _controller),
                Expanded(child: Center(child: AnimatedBuilder(
                  animation: _controller,
                  builder: (context,child){
                    switch(_controller.selectedIndex){
                      case 0: _key.currentState?.closeDrawer();
                      return Center(
                        child: Text('Home',style: TextStyle(color: Colors.white,fontSize: 40),),
                      );
                      case 1: _key.currentState?.closeDrawer();
                      return Center(
                        child: Text('Search',style: TextStyle(color: Colors.white,fontSize: 40),),
                      );
                      case 2: _key.currentState?.closeDrawer();
                      return Center(
                        child: Text('Settings',style: TextStyle(color: Colors.white,fontSize: 40),),
                      );
                      case 3: _key.currentState?.closeDrawer();
                      return Center(
                        child: Text('Theme',style: TextStyle(color: Colors.white,fontSize: 40),),
                      );
                      default:
                        return Center(
                          child: Text('Home',style: TextStyle(color: Colors.white,fontSize: 40),),
                        );
                    }
                  },
                ),))
              ],
            )
          );
        }
      ),
    );
  }
}

class SideBarXExample extends StatelessWidget {
  const SideBarXExample({Key? key, required SidebarXController controller}) : _controller = controller,super(key: key);
  final SidebarXController _controller;
  @override
  Widget build(BuildContext context) {
    return SidebarX(
      controller: _controller,
      theme:  const SidebarXTheme(
        decoration: BoxDecoration(
            color: canvasColor,
            borderRadius: BorderRadius.only(topRight: Radius.circular(20),bottomRight: Radius.circular(20))
        ),
        iconTheme: IconThemeData(
          color: Colors.white,
        ),
        selectedTextStyle: const TextStyle(color: Colors.white),
      ),
      extendedTheme: const SidebarXTheme(
          width: 250
      ),

      footerDivider: Divider(color:  Colors.white.withOpacity(0.8), height: 1),
      headerBuilder: (context,extended){
        return const  SizedBox(
          height: 100,
          child: Icon(Icons.person,size: 60,color: Colors.white,),
        );
      },

      items: const [
        SidebarXItem(icon: Icons.home, label: 'Home',),
        SidebarXItem(icon: Icons.search, label: 'Search'),
        SidebarXItem(icon: Icons.settings, label: 'Setting'),
        SidebarXItem(icon: Icons.dark_mode, label: 'Light/Dark Mode'),
      ],
    );
  }
}

Flutter Form Email Validation RealTime – using regex pattern

0
flutter email validation using regular expression

Hi Guys, Welcome to Proto Coders Point. This Article is on How to Validate email TextField in flutter.

We will use RegExp to validate email textfield, This will be a real time email validation form as user is typing in the form we will check the validation for every string the user enter.

email regex pattern for email validation

r'\S+@\S+\.\S+'

Source Code – Form Email Validation Flutter

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      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> {

  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
  //TextController to read text entered in text field
  TextEditingController textEditingControllerEmail = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Form(
            key: _formkey,
            child: Padding(
              padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
              child: TextFormField(
                controller: textEditingControllerEmail,
                onChanged: (val){
                  _formkey.currentState?.validate();
                },
                keyboardType: TextInputType.text,
                decoration:buildInputDecoration(Icons.email,"Email"),
                validator: (value){
                print(value);
                  if(value!.isEmpty){
                    return "Please Enter Email";
                  }else if(!RegExp(r'\S+@\S+\.\S+').hasMatch(value))
                    {
                      return "Please Enter a Valid Email";
                    }
                  return null;
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// TextFormField Border Decoration
InputDecoration buildInputDecoration(IconData icons,String hinttext) {
  return InputDecoration(
    hintText: hinttext,
    prefixIcon: Icon(icons),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
          color: Colors.green,
          width: 1.5
      ),
    ),
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
    enabledBorder:OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
  );
}

I above code, A have created GlobalKey with formState and a TextEditingController using which we can get the text been entered in TextField.

Then In UI I have A Form widget assigned a key to it. The form Widget has children i.e. TextFormField where the user will enter his email address.

In TextFormField will use validator property where will check if the enter text in textField matches with email validate regular expression.

Then will use TextFormField onChanged() and call form.currentState.validate() function to keep checking the text entered by the user.

Result

flutter email validation
flutter email validation using regular expression
flutter email validation using regular expression
flutter email validation using regular expression

Check out Similar Articles on Validation

Flutter Password Validation

Flutter Form Validation

Flutter Email Validation using plugin

Flutter IOS info.plist path in flutter project structure

0
info.plist path in flutter project

Hi Guys, Welcome to Proto Coders Point. In flutter project structure IOS info.plist file path location is:-

<Project>/ios/Runner/Info.plist

flutter project do not contain IOS folder (flutter IOS folder missing). You might have forgot to tick IOS while creating new flutter project in android studio/VSCode.

No Issue, you can create IOS folder in existing flutter project by running below command by being into Root Folder of project:-

flutter create -i swift

What is Info.plist file used for

In flutter IOS Info.plist file is useful to provide application metadata to the system. plist files syntax is in XML format. IOS & Flutter developer mostly use Info.plist file when they need special permission to implement certain feature in app (like accessing camera, microphone, accessing gallery, use for Bluetooth)

Flutter dart sort map by key or values Ascending/Descending order

0
Flutter map sort by key or values

Hi Guy’s Welcome to Proto Coders Point, In this dart article let’s checkout how to sort a map by its value.

Suppose you have a map like this:

final Map<String,int> mayData = {
    'a' : 100,
    'b' : 90,
    'c' : 50,
    'd' : 150,
    'e' : 200,
    'r' : 600,
  };

And your task is to sort this map in a form of ascending/descending order as per the project requirement.

The solution to sort map values in ascending or descending order is quite easily & simple then you thing it is.

Flutter Dart Sort map in ascending order by its values

Video Tutorial

void main() {
  final Map<String,int> mapData = {
    'a' : 100,
    'b' : 90,
    'c' : 50,
    'd' : 150,
    'e' : 200,
    'f' : 600,
  };
  
  // sorting the map value in ascending order by it's value.
  
  // convert the map data into list(array).
  
  List<MapEntry<String,int>> listMappedEntries = mapData.entries.toList();
  
  // Now will sort the list
  
  listMappedEntries.sort((a,b)=> a.value.compareTo(b.value));
  // list is been sorted
  
  // now convert the list back to map after sorting.
  
  final Map<String,int> sortedMapData = Map.fromEntries(listMappedEntries);
  
  print(sortedMapData);
}

Output

flutter map value sorting ascending

Flutter Dart Sort map in descending order by its values

The code is similar to above example, The only thing is while sorting compering, We must compare reverse i.e.

Instead if this:

  listMappedEntries.sort((a,b)=> a.value.compareTo(b.value))

Do this:

  listMappedEntries.sort((a,b)=> b.value.compareTo(a.value))

Video Tutorial

https://youtu.be/EnNYKnXaSRc

Complete Code

void main() {
  final Map<String,int> mapData = {
    'a' : 100,
    'b' : 90,
    'c' : 50,
    'd' : 150,
    'e' : 200,
    'f' : 600,
  };
  
  // sorting the map value in ascending order by it's value.
  
  // convert the map data into list(array).
  
  List<MapEntry<String,int>> listMappedEntries = mapData.entries.toList();
  
  // Now will sort the list in descending order
  
  listMappedEntries.sort((a,b)=> b.value.compareTo(a.value));
  // list is been sorted
  
  // now convert the list back to map after sorting.
  
  final Map<String,int> sortedMapData = Map.fromEntries(listMappedEntries);
  
  print(sortedMapData);
}

Output

flutter map value sorting descending

Flutter map sort by key example

All you need to do is use inbuilt sort function and compare map key with key, and thus map will get sorted by key.

listMappedEntries.sort((a,b)=> a.key.compareTo(b.key));

Complete Code

void main() {
  final Map<String,int> mapData = {
    'a' : 100,
    'z' : 90,
    'f' : 50,
    'b' : 150,
    'n' : 200,
    'r' : 600,
  };
  
  // sorting the map value in ascending order by it's value.
  
  // convert the map data into list(array).
  
  List<MapEntry<String,int>> listMappedEntries = mapData.entries.toList();
  
  // dart map sort by key
  
  listMappedEntries.sort((a,b)=> a.key.compareTo(b.key));
  
  // list is been sorted
  
  // now convert the list back to map after sorting.
  
  final Map<String,int> sortedMapData = Map.fromEntries(listMappedEntries);
  
  print(sortedMapData);
}

Output

Flutter map sort by key example

Similar Article Recommended

Flutter Map

Sum of all values in map flutter

flutter google maps

Flutter Long Press on Widget show context popup menu item

0
Flutter On Long Press Show Popup Menu Items
gestureDetector long press show menu

Hi Guys, Welcome to Proto Coders Point. In this Flutter article let’s learn how to show popup menu item on long press on a widget.

There might be a requirement in flutter app development. i.e. when a user long press on a widget we should show a context menu item, & the position of flutter popup menu should be near by the long tapped location of the screen.

Video Tutorial

Flutter popup menu on long press

To get screen tapped position i.e. X & Y Coordinates will make use of a widget called as GestureDetector. You just need to wrap a widget with GestureDetector on which user can long press to get popup context menu near to the tapped position.

Snippet Code:

 GestureDetector(
                    onTapDown: (position)=>{
                      _getTapPosition(position)  /* get screen tap position */
                    },onLongPress: ()=>{
                    _showContextMenu(context)   /* action on long press 
                  },
 
                  child: Image.network('https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?cs=srgb&dl=pexels-anjana-c-674010.jpg&fm=jpg',width: 300,height: 300,)
                  )

Function – Flutter Get Tap position X & Y Coordinates

The below function will help us in getting user tap position i.e. X & Y coordinate of our mobile screen.

Snippet Code:

void _getTapPosition(TapDownDetails tapPosition){
     final RenderBox referenceBox = context.findRenderObject() as RenderBox;
     setState(() {
       _tapPosition = referenceBox.globalToLocal(tapPosition.globalPosition);   // store the tap positon in offset variable
       print(_tapPosition);
     });
  }

Flutter popup menu on long press at tap position

The below function will show a popup context menu item at long press position on the screen.

In out function, will use a in-built function i.e. showMenu that will help use in showing context menu items.

In showMenu function, we need to pass 3 parameter:

  • context:
  • position: /* position where user have long pressed to load popup menu items. /*
  • items: /* list of popupmenuItem */

Menu function snippet code

Snippet Code:

void _showContextMenu(BuildContext context) async {
    final RenderObject? overlay =
        Overlay.of(context)?.context.findRenderObject();
    
    final result = await showMenu(
        context: context,
        position: RelativeRect.fromRect(
            Rect.fromLTWH(_tapPosition.dx, _tapPosition.dy, 100, 100),
            Rect.fromLTWH(0, 0, overlay!.paintBounds.size.width,
                overlay!.paintBounds.size.height)),
        items: [
          const PopupMenuItem(
            child: Text('Add Me'),
            value: "fav",
          ),
          const PopupMenuItem(
            child: Text('Close'),
            value: "close",
          )
        ]);
    // perform action on selected menu item
    switch (result) {
      case 'fav':
        print("fav");
        break;
      case 'close':
        print('close');
        Navigator.pop(context);
        break;
    }
  }

Flutter show popup context menu near long press position

Will keep it simple. Will have a Image Widget at the center of screen, The Image Widget is been wrapped with GestureDetector therefore, When user long press on image widget we get the tap position using onTapDown() & onLongPress() will popup a context menu items which 2 options (Add to favorite & a Close menu).

flutter long press show popup menu items

Complete Source Code

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  Offset _tapPosition = Offset.zero;

  void _getTapPosition(TapDownDetails tapPosition) {
    final RenderBox referenceBox = context.findRenderObject() as RenderBox;
    setState(() {
      _tapPosition = referenceBox.globalToLocal(tapPosition.globalPosition);
      print(_tapPosition);
    });
  }

  void _showContextMenu(BuildContext context) async {
    final RenderObject? overlay =
        Overlay.of(context)?.context.findRenderObject();

    final result = await showMenu(
        context: context,
        position: RelativeRect.fromRect(
            Rect.fromLTWH(_tapPosition.dx, _tapPosition.dy, 100, 100),
            Rect.fromLTWH(0, 0, overlay!.paintBounds.size.width,
                overlay!.paintBounds.size.height)),
        items: [
          const PopupMenuItem(
            child: Text('Add Me'),
            value: "fav",
          ),
          const PopupMenuItem(
            child: Text('Close'),
            value: "close",
          )
        ]);
    // perform action on selected menu item
    switch (result) {
      case 'fav':
        print("fav");
        break;
      case 'close':
        print('close');
        Navigator.pop(context);
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('ProtoCodersPoint.com'),
          centerTitle: true,
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                    onTapDown: (position) => {_getTapPosition(position)},
                    onLongPress: () => {_showContextMenu(context)},
                    onDoubleTap: () => {_showContextMenu(context)},
                    child: Image.network(
                      'https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?cs=srgb&dl=pexels-anjana-c-674010.jpg&fm=jpg',
                      width: 300,
                      height: 300,
                    ))
              ],
            ),
          ),
        ));
  }
}

How to give border to listTile flutter

0
How to Give Borders to ListTile
How to Add Borders to ListTile

Hi Guys, Welcome to Proto Coders Point, In tis Flutter article let’s check out how to add border to flutter listTile widget.

Flutter ListTile

A ListTile in flutter container properties widget such as Text, Leading, Trailing Widget(Icon). ListTile first property i.e. title is mandatory & other properties like subTitle, leading, trailing are optional.

Video Tutorial

This is How ListTile looks without custom design

Code:

ListTile(
                  iconColor: Colors.white,
                  leading: Icon(Icons.ac_unit_sharp,size: 25,),
                  title: Text('Normal ListTile',style: TextStyle(color: Colors.white),),
                  subtitle: Text("This is Sub Title",style: TextStyle(color: Colors.white),),
                  trailing: Icon(Icons.arrow_forward_rounded),
       ),
flutter listtile

Adding Border to Flutter ListTile Widget

You can easily give border to listTile by using shape property of listTile widget.

In ListTile shape property you can either use RoundedRectangleBorder, Stadium Border or BeveledRectangedBorder & assign customization to Border thinkness, Change in border color, & border Radius.

For Example Refer below snippet Code

How to give border to listTile in flutter

1. Beveled Rectangle Border ListTile

ListTile(
                  iconColor: Colors.white,
                  shape: BeveledRectangleBorder(
                    side: BorderSide(color: Colors.orange,width: 1)
                  ),
                  leading: Icon(Icons.ac_unit_sharp,size: 25,),
                  title: Text('Beveled Rectangle Border',style: TextStyle(color: Colors.white),),
                  subtitle: Text("This is Sub Title",style: TextStyle(color: Colors.white),),
                  trailing: Icon(Icons.arrow_forward_rounded),
        ),
beveled Rectangle border listtile
beveled Rectangle border listtile

2. Rounded Rectangle Border ListTile

ListTile(
                  iconColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white,width: 2),
                    borderRadius: BorderRadius.circular(20)
                  ),
                  leading: Icon(Icons.ac_unit_sharp,size: 25,),
                  title: Text('Rounded Rectangle Border',style: TextStyle(color: Colors.white),),
                  subtitle: Text("This is Sub Title",style: TextStyle(color: Colors.white),),
                  trailing: Icon(Icons.arrow_forward_rounded),
      ),
rounded rectangle border listtile
rounded rectangle border listtile

3. Card with Rounder Rectangle Border radius ListTile

Card(
       shape: RoundedRectangleBorder(
              side: BorderSide(color: Colors.redAccent,width: 2),
              borderRadius: BorderRadius.circular(20)
           ),
           child: const ListTile(
            iconColor: Colors.black,
            leading: Icon(Icons.ac_unit_sharp,size: 25,),
            title: Text('Card Rounded Rectangle Border',style: TextStyle(color: Colors.black),),
            subtitle: Text("This is Sub Title",style: TextStyle(color: Colors.black54),),
            trailing: Icon(Icons.arrow_forward_rounded),
      ),
  ),
card rounded rectangle border listtile
card rounded rectangle border listtile

4. Stadium Border ListTile

const ListTile(
                  iconColor: Colors.white,
                  shape: StadiumBorder(
                    side: BorderSide(color: Colors.red,width: 3)
                  ),
                  leading: Icon(Icons.ac_unit_sharp,size: 25,),
                  title: Text('Stadium Border',style: TextStyle(color: Colors.white),),
                  subtitle: Text("This is Sub Title",style: TextStyle(color: Colors.white),),
                  trailing: Icon(Icons.arrow_forward_rounded),
       ),
stadium border listtile
stadium border listtile