Author

admin

Browsing

Awesome & Simple Flutter Notes App Using Provider, Sqflite and ImagePicker

flutter notes - note taking app
This post contains affiliate links. If you use these links to buy something I may earn a commission. Thanks.”

Let’s learn more about Flutter by making a Note-taking app. Using this app

  • You can create, edit and delete notes.
  • Takes photos from gallery or using camera
  • Notes save into database using Provider

It’s going to be a long tutorial. So grab a cup of coffee and snacks.

Okay…Let’s start.

In this post, you will learn about more widgets and flutter packages like Provider, Sqflite, and ImagePicker.

Don’t worry about those words haven’t you heard about it. I will talk about that while making.

If you want more information about Flutter in less time. You can go for it. The author’s style of approach is nice and provides good content
.
.
.
.
Download Source Code – Subscribe to our Newsletter – Link will send it to you

A quick demo
flutter notes - how it works - screens

Okay… Let’s make a simple Flutter project named “flutter_notes“.

If you don’t know how to make a Flutter project read this command guide and Flutter Android Studio setup guide.

Now just open pubspec.yaml file and put below packages like given below in dependencies section.

Spacing or indent is more important here, so if you don’t do it well, it will give you an error. Save the file and click on pub get.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  
  google_fonts: ^1.1.0
  image_picker: ^0.6.7+11
  intl: ^0.16.1
  path: ^1.7.0
  path_provider: ^1.6.18
  provider: ^4.3.2+2
  sqflite: ^1.3.1+1
  url_launcher: ^5.7.2

What above packages will do?

  • google_fonts: helps us to include fonts from fonts.google.com, there is no need for storing fonts in assets folder.
  • image_picker: assist us to take image from our device gallery and using Camera.
  • intl: Used to format Date and Time (usage – in this app).
  • path: Helps us to join path(usage – in this app).
  • path_provider: It gives directory location to store images(usage- in this app).
  • provider: It’s used to state management. Google recommended package.
  • sqflite: App stores data in sqlite database. Sqflite package helps us to implement all CRUD operations
  • url_launcher: helps to open a URL in a browser or webview. Not for only lauching web pages, you can mail, call, and message too.

Now let’s creates directories for categorizing dart files. flutter notes - projects structure Create helper, models, screens, utils, widgets directories, and create dart files inside it. helper directory contains two dart files – database_helper.dart, and note_provider.dart.

  • database_helper.dart – It contains all database related operations.
  • note_provider.dart – Code contains to add, update and delete operations and notify the listeners.

models directory contains a note file.

  • note.dart – It holds id, title, content, date, and image location.

screen directory contains 3 screens or pages whatever you call. flutter note edit screen

    • note_edit_screen.dart – This screen used to create and update note.

    • note_list_screen.dart – This is the Main Screen, it lists your notes.

  • note_view_screen.dart – Page used to read notes.

utils directory contains constants data.

  • constants.dart – It lists style constants and color values.

widget directory contains delete_popup.dart and list_item.dart. flutter alertdialog - delete note

    • delete_popup.dart – Just like the name, it shows alertdialog when the delete note button clicks.

list item flutter note taking app

    • list_item.dart – Your each note represented using this file in list.

So now you got the idea of how this Flutter notes app works. Then let’s start coding… Now we will create each file one by one and explaining how the code works. So keep calm and code… Let’s partially make 3 screens. I assume that you have created all directories and files. So it’s time to code note_list_screen.dart.

  • Type ‘stless” and press Enter key.
  • Change to below code
import 'package:flutter/material.dart';

class NoteListScreen extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {

    return FutureBuilder();

      }

}

  • Here we are going to use FutureBuilder widget. Depends on the state it will show UI to us

note_edit_screen.dart

  • “stful” for stateful widget.

 

import 'package:flutter/material.dart';
class NoteEditScreen extends StatefulWidget
{
  static const route = '/edit-note';
  @override
  _NoteEditScreenState createState() => _NoteEditScreenState();
}
class _NoteEditScreenState extends State {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

note_view_screen.dart

import 'package:flutter/material.dart';

class NoteViewScreen extends StatefulWidget {
  static const route = '/note-view';

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

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


This is just a start.. let’s create Note model. note.dart

import 'package:intl/intl.dart';

class Note {
  int _id;
  String _title;
  String _content;
  String _imagePath;

  Note(this._id, this._title, this._content, this._imagePath);

  int get id => _id;
  String get title => _title;
  String get content => _content;
  String get imagePath => _imagePath;

  String get date {
    final date = DateTime.fromMillisecondsSinceEpoch(id);
    return DateFormat('EEE h:mm a, dd/MM/yyyy').format(date);
  }
}
  • Here _id should be unique one. So It’s better to use note created time.
  • _title stores title of the note, _content – content of the note and _imagePath stores location of image

okay… Now move to the backend and create a database. database_helper.dart

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static Future database() async {
    final databasePath = await getDatabasesPath();

    return openDatabase(join(databasePath, 'notes_database.db'),
        onCreate: (database, version) {
          return database.execute(
              'CREATE TABLE notes(id INTEGER PRIMARY KEY, title TEXT, content TEXT, imagePath TEXT)');
        }, version: 1);
  }

  static Future<List<Map<String, dynamic>>> getNotesFromDB() async {
    final database = await DatabaseHelper.database();

    return database.query("notes", orderBy: "id DESC");
  }

}

  • databasePath stores location of both Android and iOS directory location and we will add it with our database name notes_database.db using path package join() method
  • stores id as Integer, others as TEXT format. Using id as Primary Key is considered as good practice.
  • In getNotesFromDB() method – just create a database instance and calls query() method in Descending order
  • id must be DateTime integer value, So we can sort notes based on Descending order of dates.
  • getNotesFromDB() method finally returns List of Map values

note_provider.dart

import 'package:flutter/material.dart';
import 'package:flutter_notes/helper/database_helper.dart';
import '../models/note.dart';

class NoteProvider with ChangeNotifier {
  List _items = [];

  List get items {
    return [..._items];
  }

  Future getNotes() async {
    final notesList = await DatabaseHelper.getNotesFromDB();

    _items = notesList
        .map(
          (item) =>
          Note(
              item['id'], item['title'], item['content'], item['imagePath']),
    )
        .toList();

    notifyListeners();
  }
}
  • Using getNotes() method, we can get our notes fromDatabase. After converting to List objects it passes to _items list.
  • Calling notifyListeners() will rebuild the listeners.

Now we need to provide the provider inside main.dart file. So let’s move on to main.dart. Clear the whole code inside that and paste the below code. main.dart

import 'package:flutter/material.dart';
import 'package:flutter_notes/helper/note_provider.dart';
import 'package:flutter_notes/screens/note_list_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_notes/screens/note_edit_screen.dart';
import 'package:flutter_notes/screens/note_view_screen.dart';


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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: NoteProvider(),
      child: MaterialApp(
        title: "Flutter Notes",
        debugShowCheckedModeBanner: false,
        initialRoute: '/',
        routes: {
          '/': (context) => NoteListScreen(),
          NoteViewScreen.route: (context) => NoteViewScreen(),
        NoteEditScreen.route: (context) => NoteEditScreen(),

        },
      ),
    );
  }
}


Just implement the loading screen inside NoteListScreen like below. don’t worry about those red lines, after you importing the packages declarations it will be okay. Here that will be import ‘package:flutter_notes/helper/note_provider.dart’;, import ‘package:provider/provider.dart’;

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
     future: Provider.of<NoteProvider>(context,listen: false).getNotes(),
      builder: (context,snapshot)
      {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }else
          {
            return Container(
                         );
          }

      },
    );
  }

Let’s run now.

  • You can see CircularProgressIndicator loading now.
  • Here FutureBuilder widget used to build our UI. It needs a future as input, that’s why we have set getNotes() as input.
  • While getNotes() loading, builder will provide connectionstate. Using connectionState wec can change our UI.
  • When ConnectionState.waiting gets we will load CircularProgressIndicator(),that’s why you have seen a ProgressIndicator now.
  • When the ConnectionState changes, it shows a black screen. That is our Container, because build method always needs a Widget.

Let’s create our header before that place some constant values inside constants.dart file constants.dart

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

const grey = Color(0xFFEAEAEA);
const grey2 = Color(0xFF6D6D6D);
const black = Color(0xFF1C1C1C);
const black2 = Color(0xFF424242);
const headerColor = Color(0xFFFD5872);
const white = Colors.white;

var headerRideStyle = GoogleFonts.roboto(
  textStyle: TextStyle(
    color: white,
    fontSize: 15.0,
  ),
);

var headerNotesStyle = GoogleFonts.roboto(
  textStyle: TextStyle(
    color: white,
    fontSize: 45.0,
    fontWeight: FontWeight.bold,
  ),
);

enum EditMode {
  ADD,
  UPDATE,
}

var noNotesStyle = GoogleFonts.roboto(
  textStyle: TextStyle(
    fontSize: 22.0,
    color: black2,
    fontWeight: FontWeight.w600,
  ),
);
var boldPlus = GoogleFonts.roboto(
  textStyle: TextStyle(
    fontSize: 30.0,
    color: Colors.blueAccent,
    fontWeight: FontWeight.bold,
  ),
);
var itemTitle = GoogleFonts.roboto(
  textStyle: TextStyle(
    fontSize: 18.0,
    color: black,
    fontWeight: FontWeight.bold,
  ),
);

var itemDateStyle = GoogleFonts.roboto(
  textStyle: TextStyle(
    fontSize: 11.0,
    color: grey2,
  ),
);

var itemContentStyle = GoogleFonts.roboto(
  textStyle: TextStyle(
    fontSize: 15.0,
    color: grey2,
  ),
);

var viewTitleStyle = GoogleFonts.roboto(
  fontWeight: FontWeight.w900,
  fontSize: 28.0,
);

var viewContentStyle = GoogleFonts.roboto(
    letterSpacing: 1.0,
    fontSize: 20.0,
    height: 1.5,
    fontWeight: FontWeight.w400);

var createTitle = GoogleFonts.roboto(
    textStyle: TextStyle(
  fontSize: 28.0,
  fontWeight: FontWeight.w900,
));

var createContent = GoogleFonts.roboto(
  textStyle: TextStyle(
    letterSpacing: 1.0,
    fontSize: 20.0,
    height: 1.5,
    fontWeight: FontWeight.w400,
  ),
);

var shadow = [
  BoxShadow(
    color: Colors.grey[300],
    blurRadius: 30,
    offset: Offset(0, 10),
  )
];


header list Header Item will show ANDROIDRIDE’S NOTES – when You tap on it, it will show you AndroidRide’s home page. Let’s create a method called header() inside NoteListScreen and don’t forget to import constants.dart file.

Widget header() {
    return GestureDetector(
      onTap: _launchUrl,
      child: Container(
        decoration: BoxDecoration(
          color: headerColor,
          borderRadius: BorderRadius.only(
            bottomRight: Radius.circular(75.0),
          ),
        ),
        height: 150,
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'ANDROIDRIDE\'S',
              style: headerRideStyle,
            ),
            Text(
              'NOTES',
              style: headerNotesStyle,
            ),
          ],
        ),
      ),
    );
  }

  • Here I used GestureDetector that help us to detect if someone taps on it Then it will trigger onTap.

Now you will get a small error due to launchUrl. because We haven’t defined that one. Let’s check how to do that? First we need to import the below line:

import 'package:url_launcher/url_launcher.dart';

then add the below code.

_launchUrl() async {
    const url = 'https://www.androidride.com';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  • _launchUrl() loads ‘https://www.androidride.com’ in your browser, if not it will throw an error.

Okay…Now our NoteListScreen shows CircularProgressIndicator when getting Notes. We don’t need to show a Container if the process is done? Let’s change it and Show a UI indicating that shows there is no note available. Let’s create another method that shows a loud crying emoji with no notes available message. before that, we must include emoji image, other styling constants, and import flutter gestures.dart’ too. emoji image in assets folder Let’s add the image. Create an assets folder and paste it there. You can use any image, if you want an emoji image – you can download our code through subscribing our email. image in pubspec.yaml flutter Add the image in pubspec.yaml file then only the app knows where is your image file.

  # To add assets to your application, add an assets section, like this:
  assets:
     - crying_emoji.png
  #   - images/a_dot_ham.jpe
Widget noNotesUI(BuildContext context) {
    return ListView(
      children: [
        header(),
        Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 50.0),
              child: Image.asset(
                'crying_emoji.png',
                fit: BoxFit.cover,
                width: 200,
                height: 200,
              ),
            ),
            RichText(
              text: TextSpan(
                style: noNotesStyle,
                children: [
                  TextSpan(text: ' There is no note available\nTap on "'),
                  TextSpan(
                      text: '+',
                      style: boldPlus,
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          goToNoteEditScreen(context);
                        }),
                  TextSpan(text: '" to add new note'),
                ],
              ),
            )
          ],
        ),
      ],
    );
  }


import 'package:flutter/gestures.dart';

import gestures.dart for TapGestureRecognizer error. Don’t worry about goToNoteEditScreen(), which will clear after explaining the above code.

  • It shows header, emoji image and no note available message.
  • Padding widget provides empty space above the image.
  • RichText has recognizer property, that we can use to detect tap events. That’s why gestures.dart we added.

Solve the error now.

void goToNoteEditScreen(BuildContext context) {
     Navigator.of(context).pushNamed(NoteEditScreen.route);
  }

  • It pushes NoteEditScreen() on the stack.
  • So when you tap on the blue + button, then it will show NoteEditScreen.

We have already implemented creating database and showing CircularProgressIndicator. You know that we haven’t created any notes. So It’s time to show noNotesUI() method. So just copy and replace the code with existing build method inside NoteListScreen.

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
     future: Provider.of<NoteProvider>(context,listen: false).getNotes(),
      builder: (context,snapshot)
      {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        else
        {
          if(snapshot.connectionState == ConnectionState.done)
          {
            return Scaffold(
              body: Consumer<NoteProvider>(
                child: noNotesUI(context),
                builder: (context, noteprovider, child) =>
                noteprovider.items.length <= 0
                    ? child
                    : Container(),
              ),
              floatingActionButton: FloatingActionButton(
                onPressed: () {
                  goToNoteEditScreen(context);
                },
                child: Icon(Icons.add),
              ),
            );
          }
            return Container(
              width: 0.0,
              height: 0.0,
            );
          }

      },
    );
  }


  • When the ConnectionState becomes ConnectionState.done, second block of code executes.
  • When the notes count is less than equal to zero. It shows child in builder property, that is noNotesUI(context) method.

If you run the project now, After showing progress, It will show noNotesUI such as header, emoji, and message. It’s time to create NoteEditScreen. Just paste the below code. note_edit_screen.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_notes/helper/note_provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_notes/utils/constants.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'note_view_screen.dart';
class NoteEditScreen extends StatefulWidget {
  static const route = '/edit-note';
  @override
  _NoteEditScreenState createState() => _NoteEditScreenState();
}
class _NoteEditScreenState extends State {
  final titleController = TextEditingController();
  final contentController = TextEditingController();
  File _image, localFile;
  final picker = ImagePicker();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: white,
      appBar: AppBar(
        elevation: 0.7,
        backgroundColor: Colors.white,
        leading: IconButton(
          onPressed: () => Navigator.of(context).pop(),
          icon: Icon(Icons.arrow_back),
          color: Colors.black,
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.photo_camera),
            color: Colors.black,
            onPressed: () {
              getImage(ImageSource.camera);
            },
          ),
          IconButton(
            icon: Icon(Icons.insert_photo),
            color: Colors.black,
            onPressed: () {
              getImage(ImageSource.gallery);
            },
          ),
          IconButton(
            icon: Icon(Icons.delete),
            color: Colors.black,
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.only(
                  left: 10.0, right: 5.0, top: 10.0, bottom: 5.0),
              child: TextField(
                controller: titleController,
                maxLines: null,
                textCapitalization: TextCapitalization.sentences,
                style: createTitle,
                decoration: InputDecoration(
                    hintText: 'Enter Note Title', border: InputBorder.none),
              ),
            ),
            if(_image != null)
              Container(
                padding: EdgeInsets.all(10.0),
                width: MediaQuery
                    .of(context)
                    .size
                    .width,
                height: 250.0,
                child: Stack(
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20.0),
                        image: DecorationImage(
                          image: FileImage(_image),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.bottomRight,
                      child: Padding(
                        padding: EdgeInsets.all(12.0),
                        child: Container(
                          height: 30.0,
                          width: 30.0,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.white,
                          ),
                          child: InkWell(
                            onTap: () {
                              setState(
                                    () {
                                  _image = null;

                                },
                              );
                            },
                            child: Icon(
                              Icons.delete,
                              size: 16.0,
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            Padding(
              padding: const EdgeInsets.only(
                  left: 10.0, right: 5.0, top: 10.0, bottom: 5.0),
              child: TextField(
                controller: contentController,
                maxLines: null,
                style: createContent,
                decoration: InputDecoration(
                  hintText: 'Enter Something...',
                  border: InputBorder.none,
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (titleController.text.isEmpty)
            titleController.text = 'Untitled Note';
          saveNote();
        },
        child: Icon(Icons.save),
      ),
    );
  }

  @override
  void dispose() {
    titleController.dispose();
    contentController.dispose();
    super.dispose();
  }
}
  • Now we have to solve 2 methods. getImage() and saveNote().
  • Before that, TextEditingController helps to get data from TextField. TextEditingController should be dispose in dispose() method.
  • You can hide and show using Visibility widget too.

Before using image_picker, it’s better to check the documentation. We need to add following keys to info.plist file, located in /ios/Runner/Info.plist ios permission for image picker

        NSPhotoLibraryUsageDescription
	Need to take Picture from Gallery
	NSCameraUsageDescription
	Need to take Picture using Camera
 void getImage(ImageSource imageSource) async {
    PickedFile imageFile = await picker.getImage(source: imageSource);

    if (imageFile == null) return;

    File tmpFile = File(imageFile.path);
    final appDir = await getApplicationDocumentsDirectory();
    final fileName = basename(imageFile.path);

    localFile = await tmpFile.copy('${appDir.path}/$fileName');

    setState(() {
      _image = localFile;
    
    });
  }

  • Above code get the Image File if it’s from camera or gallery, and copies to a directory in both Android and iOS .
  • After copying image file, setState() called. It will trigger rebuild method.
  • That’s how Image shows in this screen.
  void saveNote() {
    String title = titleController.text.trim();
    String content = contentController.text.trim();
    String imagePath = _image != null ? _image.path : null;

      int id = DateTime
          .now()
          .millisecondsSinceEpoch;
      Provider.of<NoteProvider>(this.context, listen: false)
          .addOrUpdateNote(id, title, content, imagePath, EditMode.ADD);
      Navigator.of(this.context)
          .pushReplacementNamed(NoteViewScreen.route, arguments: id);
    }

  • In saveNote() – we will save title, content and Image location and gives to provider class.
  • DateTime.now().millisecondsSinceEpoch – gives integer number will save as note id.
  • EditMode.ADD – means just inserting a new note.
  • Using Navigator, NoteViewScreen will loaded, id also passed.

Open note_provider.dart and paste the below code.

  Future addOrUpdateNote(int id, String title, String content,
      String imagePath, EditMode editMode) async {
    final note = Note(id, title, content, imagePath);

    if (EditMode.ADD == editMode) {
      _items.insert(0, note);
    } else {
      _items[_items.indexWhere((note) => note.id == id)] = note;
    }

    notifyListeners();

    DatabaseHelper.insert(
      {
        'id': note.id,
        'title': note.title,
        'content': note.content,
        'imagePath': note.imagePath,
      },
    );
  }

  • Here, EditMode is ADD, then it will added to list as the first item. Otherwise, it will updated with the existing note.
  • notifyListeners() triggers all Listeners. Most important our ListView, haven’t added yet.
  • Create insert() method in database_helper.dart.
static Future insert(Map<String, Object> data) async {
    final database = await DatabaseHelper.database();

    database.insert("notes", data,
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  • database instance created and Note map value is inserted into database
  • ConflictAlgorithm.replace – It will replace the data when a unique constraint violation occurs. Here when id found twice.

You can run now. When the note is saved a black screen will appear that’s our NoteViewScreen. What we need now? We need to show the note in ListView. The note will represent in ListItem widget, let’s create that one.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_notes/helper/note_provider.dart';
import 'package:flutter_notes/screens/note_edit_screen.dart';
import 'package:flutter_notes/screens/note_view_screen.dart';
import 'package:provider/provider.dart';
import '../utils/constants.dart';
class ListItem extends StatelessWidget {
  final int id;
  final String title;
  final String content;
  final String imagePath;
  final String date;
  ListItem({this.id, this.title, this.content, this.imagePath, this.date});
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 135.0,
      margin: EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
      child: InkWell(
        onTap: () {
          Navigator.pushNamed(context, NoteViewScreen.route, arguments: id);
        },
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(horizontal: 12.0),
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: shadow,
            borderRadius: BorderRadius.circular(15.0),
            border: Border.all(color: grey, width: 1.0),
          ),
          child: Row(
            children: [
              Expanded(
                child: Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                        style: itemTitle,
                      ),
                      SizedBox(height: 4.0),
                      Text(
                        date,
                        overflow: TextOverflow.ellipsis,
                        style: itemDateStyle,
                      ),
                      SizedBox(
                        height: 8.0,
                      ),
                      Expanded(
                        child: Text(
                          content,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: itemContentStyle,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              if(imagePath!=null)
              Row(
                children: [
                  SizedBox(
                    width: 12.0,
                  ),
                    Container(
                      width: 80.0,
                      height: 95.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.0),
                        image: DecorationImage(
                          image: FileImage(
                            File(imagePath),
                          ),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

  • InkWell listen for tap events and perform action on it.
  • such as it pushes NoteViewScreen with id.

Let’s build our Note ListView to show ListItems by removing Container.

Consumer(
                child: noNotesUI(context),
                builder: (context, noteprovider, child) =>
                    noteprovider.items.length <= 0
                        ? child
                        : ListView.builder(
                            itemCount: noteprovider.items.length + 1,
                            itemBuilder: (context, index) 
                            {
                              if (index == 0) 
                              {
                                return header();
                              } 
                              else 
                              {
                                final i = index - 1;
                                final item = noteprovider.items[i];
                                return ListItem(
                                  id: item.id,
                                  title: item.title,
                                  content: item.content,
                                  imagePath: item.imagePath,
                                  date: item.date,
                                );
                              }
                            },
                          ),
              ),

It’s time to talk about NoteviewScreen. Whenever NoteViewScreen is open, only with a id. So we can use id to get our note from provider and database.

class _NoteViewScreenState extends State {
  Note selectedNote;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    final id = ModalRoute.of(context).settings.arguments;

    final provider = Provider.of<NoteProvider>(context);

    if (provider.getNote(id) != null) {
      selectedNote = provider.getNote(id);
    }
  }
}

  • To get id passed from other screens, use ModalRoute.of(context).settings.arguments.
  • We need to create getNote() method in note_provider.dart to access the note with id.
Note getNote(int id) {
    return _items.firstWhere((note) => note.id == id, orElse: () => null);
  }


back to NoteViewScreen, you can edit the build method using the below code. note_view_screen.dart

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: white,
      appBar: AppBar(
        elevation: 0.7,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: Icon(
              Icons.delete,
              color: Colors.black,
            ),
            onPressed: () => _showDialog(),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                selectedNote?.title,
                style: viewTitleStyle,
              ),
            ),
            Row(
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Icon(
                    Icons.access_time,
                    size: 18,
                  ),
                ),
                Text('${selectedNote?.date}')
              ],
            ),
            if (selectedNote.imagePath != null)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Image.file(File(selectedNote.imagePath)),
              ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                selectedNote.content,
                style: viewContentStyle,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushNamed(context, NoteEditScreen.route,
              arguments: selectedNote.id);
        },
        child: Icon(Icons.edit),
      ),
    );
  }

  _showDialog() {
    showDialog(
        context: this.context,
        builder: (context) {
          return DeletePopUp(selectedNote: selectedNote);
        });
  }
}


  • showDialog() method helps us to open PopUp alerting delete message.

delete_popup.dart

import 'package:flutter/material.dart';
import '../helper/note_provider.dart';
import '../models/note.dart';
import 'package:provider/provider.dart';

class DeletePopUp extends StatelessWidget {
  const DeletePopUp({
    Key key,
    @required this.selectedNote,
  }) : super(key: key);

  final Note selectedNote;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
      title: Text('Delete?'),
      content: Text('Do you want to delete the note?'),
      actions: [
        FlatButton(
          child: Text('Yes'),
          onPressed: () {
            Provider.of<NoteProvider>(context, listen: false)
                .deleteNote(selectedNote.id);
            Navigator.popUntil(context, ModalRoute.withName('/'));
          },
        ),
        FlatButton(
          child: Text('No'),
          onPressed: () {
            Navigator.pop(context);
          },
        )
      ],
    );
  }
}

  • It just shows an AlertDialog, when user clicks on Yes, Note will be deleted and back to NoteListScreen

Now we need to delete note from provider and database. So add the below line in note_provider.dart

  Future deleteNote(int id) {
    _items.removeWhere((element) => element.id == id);
    notifyListeners();
    return DatabaseHelper.delete(id);
  }

  • It checks items with the specified id, if there is any note it will be removed and notify the listeners.

database_helper.dart

  static Future delete(int id) async {
    final database = await DatabaseHelper.database();
    return database.delete('notes', where: 'id = ?', whereArgs: [id]);
  }

  • Based on the id, note will deleted from the database.

If you have checked the app you can see that you can’t edit the existing note or it won’t show content in NoteEditScreen. How to solve that problem?

bool firstTime = true;
Note selectedNote;
int id;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    if (firstTime) {
      id = ModalRoute.of(this.context).settings.arguments;

      if (id != null) {
        selectedNote =
            Provider.of<NoteProvider>(this.context, listen: false).getNote(id);

        titleController.text = selectedNote?.title;
        contentController.text = selectedNote?.content;

        if (selectedNote?.imagePath != null) {
          _image = File(selectedNote.imagePath);
       
        }
      }

      firstTime = false;
    }
  }

  • Here we check if the id is null or note. If id isn’t null, then note need to update.
  • get note based on id through provider
  • Sets title, content and image.

In saveNote() method, we need to tell that the note need to saved or updated. So update the method using below code.

  void saveNote() {
    String title = titleController.text.trim();
    String content = contentController.text.trim();
    String imagePath = _image != null ? _image.path : null;

    if (id != null) {
      Provider.of<NoteProvider>(this.context, listen: false)
          .addOrUpdateNote(id, title, content, imagePath, EditMode.UPDATE);
      Navigator.of(this.context).pop();
    } else {
      int id = DateTime.now().millisecondsSinceEpoch;
      Provider.of<NoteProvider>(this.context, listen: false)
          .addOrUpdateNote(id, title, content, imagePath, EditMode.ADD);
      Navigator.of(this.context)
          .pushReplacementNamed(NoteViewScreen.route, arguments: id);
    }


If the user deleting the note from NoteEditScreen, you must check that note is note on edit mode or update mode.

IconButton(
            icon: Icon(Icons.delete),
            color: Colors.black,
            onPressed: () {
              if (id != null) {
                _showDialog();
              } else {
                Navigator.pop(context);
              }
            },
          )

  • If id is not null, alertDialog shown up otherwise pop back
void _showDialog() {
    showDialog(
        context: this.context,
        builder: (context) {
          return DeletePopUp(selectedNote: selectedNote);
        });
  }

Finally, the code is done. now you can check it out and Enjoy adding notes with images or just text, that won’t be a problem.

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

Ultimate Guide : Flutter Padding Widget – How It Works?

flutter padding widget example tutorial
In this post, you will learn about the Flutter padding widget.

If you’re coming from a web development background or Android Development, You might familiar with the term ‘padding’ and know it’s just an attribute.

That’s all…

But in Flutter, it has more importance. That’s why they made it as a Widget.

Okay… Let’s learn more about Padding Widget.

How Flutter Padding Widget Works?

what is flutter padding widget

The padding widget gives empty space around the child widget. So if your widgets are colliding with each other and you think it is nice to add space around your widget, give it a go with Padding. Simply make your widget as a child of the Padding and give value.

That’s all.

Simple… isn’t it?

Flutter Padding Example

Let’s create a simple Flutter project with a Text Widget, the output should look like below.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Padding Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Padding Demo'),
        ),
        body: Text('Text Widget'),
      ),
    );
  }
}

Let’s add some padding or empty space around the Text widget. Just like below.
flutter paddding ex


Padding(
          padding: const EdgeInsets.all(50.0),
          child: Text('Text Widget'),
        ),

  • Here padding property takes 50.0 value through EdgeInsets.all() named constructor and it gives 50.0 padding to all sides.
  • Left=Right=Top=Bottom=50.0

Sometimes, adding a Padding widget around your child by typing might be difficult. How to simplify this problem?

Using Keyboard shortcuts.

Android Studio – Shortcut for Padding

Android Studio Shortcut For Flutter Padding Widget

  • Click on the widget (here Text) and ALT + ENTER or you can click on the light yellow bulb on the left side.
  • Select wrap with Padding.

Visual Studio – Shortcut for Padding

flutter padding visual studio shortcut

  • Click on the widget (here Text) and CTRL + . (dot key), or Click on the light yellow bulb.
  • Click on Wrap with Padding

How Padding Laid Out – Using Flutter Inspector

Open Flutter Inspector, and look at how the padding widget laid around the Text Widget.

flutter inspector android studio

  • Android studio users, click on Flutter Inspector and click on show debug paint.

  • This is how Padding provides empty space around the Text widget.

What if you need to provide padding to only one side or two or more than two?

You can use below named Constructors of EdgeInsets with Padding.

  1. EdgeInsets.all() – Provides padding to all sides around the child widget.
  2. EdgeInsets.only() – Supplies empty space only to the specified portions.
  3. EdgeInsets.symmetric() – It gives padding based on horizontal and vertical values.
  4. EdgeInsets.fromLTRB() – You can give padding to Left, Top, Right and Bottom Respectively.

How to provide padding to only specific sides – Using EdgeInsets.only

flutter padding only

  • When you need to add padding to only a specific side of the widget, use this named constructor with top, bottom, left and right parameters.
  • In this example, I have used left, top and bottom.

 Padding(
          padding: EdgeInsets.only(left:50.0, top: 30.0, bottom: 40.0),
          child: Text('Text Widget'),
        ),

EdgeInsets.symmetric()

flutter padding symmetric

  • EdgeInsets.symmetric has two parameters: horizontal – which applies padding for left and right sides.
  • vertical – which applies padding for top and bottom.

Padding(
          padding: EdgeInsets.symmetric(horizontal: 50.0, vertical: 80.0),
          child: Text('Text Widget'),
        ),

EdgeInsets.fromLTRB()

padding fromltrb

  • Using EdgeInsets.fromLTRB, you can easily specify Left, Top, Right and Bottom Respectively.

Padding(
          padding: EdgeInsets.fromLTRB(30.0,40.0,50.0,60.0),
          child: Text('Text Widget'),
        ),

Just like EdgeInsets, you can also use EdgeInsetsDirectional constructors. Look below.

EdgeInsetsDirectional.only()

edgeinsetsdirectional.only

  • EdgeInsetsDirectional.only() works same as EdgeInsets.only() – It uses start and end for left and right. That’s all.

Padding(
          padding: EdgeInsetsDirectional.only(start: 60.0, end: 80.0, top: 20.0),
          child: Text('Text Widget'),
        ),

EdgeInsetsDirectional.fromSTEB()

edgeinsetsdirectional.fromSTEB

  • STEB stands for Start, Top, End, and Bottom.

Padding(
          padding: EdgeInsetsDirectional.fromSTEB(60.0,30.0,80.0,90.0),
          child: Text('Text Widget'),
        ),

I hope you liked this article, So please share it with your friends and family.

Flutter Padding docs

5 Flutter RaisedButton Examples With Tutorial

flutter raisedbutton example

Let’s learn about Flutter RaisedButton.

RaisedButton…?

How is it look like?

How to add it to my code?

Okay… wait.

After reading this post, you will learn a lot more about RaisedButton.

then don’t waste my time. Please start.

Here we go.

Flutter RaisedButton

flutter raisedbutton

From the title, you can understand that It’s a raised button.

Yes, it is.

Actually the button appears elevated or in more detail, it placed higher than the surrounding area or page. It shows more shadow when the button is tapped.

You can also make icon using RaisedButton.

But now, let’s make a simple RaisedButton. You can create flutter project using flutter command or Android Studio.

simple raisedbutton exampl

import 'package:flutter/material.dart';

void main() => runApp(MyApp()); //application entry point, Calls MyApp

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter RaisedButton Example'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('RaisedButton'),
            onPressed: () {
              //onpressed gets called when the button is tapped.
              print("RaisedButton clicked");
            },
          ),
        ),
      ),
    );
  }
}

RaisedButton properties

1. VoidCallback onPressed

Just like FlatButton, RaisedButton invokes onPressed when button tapped. you can provide values in two ways.

  1. Using anonymous function

  2. In this way, you don’t need to specify method’s name. It’s actually helpful when you want to execute simple lines of unrepeated code.

    RaisedButton(
                child: Text('RaisedButton'),
                color: Colors.white,
                onPressed: () {
                  print("RaisedButton tapped - anonymous function");
                },
                ),
    
    
  3. By specifying the Function name

Specify the function name as onPressed value. just like below

RaisedButton(
            child: Text('RaisedButton'),
            color: Colors.white,
             onPressed: raisedButtonTapped,
          ),

void raisedButtonTapped() {
    print("RaisedButton tapped - Using function");
  }

2. VoidCallback onLongPress

It gets called when RaisedButton pressed for a finite long time. You can use those ways I have told above in onPressed property.

  1. Using Anonymous Function

  2. RaisedButton(
                child: Text('RaisedButton'),
                color: Colors.white,
                onPressed: () {},
                onLongPress: () {
                  print("RaisedButton long pressed - Using anonymous function");
                },
                
              ), 
    
  3. Using Function name

RaisedButton(
            child: Text('RaisedButton'),
            color: Colors.white,
            onPressed: () {},
            onLongPress: raisedButtonTapped,
          ),
...
..
  void raisedButtonTapped() {
    print("RaisedButton long pressed - Using function name");
  }

3. ValueChanged onHighlightChanged

raisedbutton onhighlightchanged example

onHighlightChanged property gives you true value when the button is tapped down and gives false after the release of the button.

4.Color textColor

RaisedButton textcolor examle
The textColor property helps to change text color on RaisedButton.

RaisedButton(
            onPressed: () {},
            child: Text("SIGN IN"),
            textColor: Colors.red,
          ),

5. Color disabledTextColor

flutter Raisedbutton disabled text color

It assist us to change Button’s text color when onPressed provided with a null value.

RaisedButton(
                child: Text('RaisedButton - Default Disabled Text Color'),
                onPressed: null,
              ),
              RaisedButton(
                child: Text('RaisedButton - Custom Disabled Text Color'),
                onPressed: null,
                disabledTextColor: Colors.black,
              ),

6. Color color

raisedbutton background color example

The color property used to set RaisedButton background. You can change it to a different color rather than default one.

RaisedButton(
            child: Text('RaisedButton'),
            color: Colors.yellow,
            onPressed: () {},
          ),

7. Color disabledColor

disabledcolor and text
Sometimes you need to disable the button and change it’s color, then apply disabledColor property like shown below. Just specify color as disabledColor property value.

RaisedButton(
                child: Text('RaisedButton - Default Disabled Color'),
                onPressed: null,
              ),
              RaisedButton(
                  child: Text('RaisedButton - Custom Disabled Color & Text'),
                  onPressed: null,
                  disabledTextColor: Colors.white60,
                  disabledColor: Colors.blueAccent),

8. FocusNode focusNode

It’s a focus related property, utilize focusNode property to set focus to RaisedButton. Look at the focusColor property, the given below how to use focusNode.

9.Color focusColor

focuscolor example

When RaisedButton gets the focus, focusColor property helps us to change the color of RaisedButton.


import 'package:flutter/material.dart';

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
  FocusNode _raisedFocusNode;

  @override
  void initState() {
    super.initState();
    _raisedFocusNode = FocusNode();
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "RaisedButton FocusColor Example",
      home: Scaffold(
        appBar: AppBar(
          title: Text("RaisedButton FocusColor Example"),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(18.0),
              child: TextField(
                onChanged: (value) =>
                    FocusScope.of(context).requestFocus(_raisedFocusNode),
              ),
            ),
            RaisedButton(
              color: Colors.blue,
              focusNode: _raisedFocusNode,
              focusColor: Colors.red,
              child: Text("DONE"),
              onPressed: () {
                print("RaisedButton clicked");
              },
            )
          ],
        ),
      ),
    );
  }
}

  • When you enter a key in TextField, it calls onChanged and make request to the _raisedFocusNode
  • RaisedButton’s focusNode value is _raisedFocusNode. When the RaisedButton gets focus, focusColor invokes and shows Red color

10.Color hoverColor

Use this property to change color when the pointer is hovering over the button. There is no hovering action in Mobile devices.

11.Color highlightColor

highlight color

highlightColor property uses to highlight the RaisedButton When it tapped.

RaisedButton(
          padding: EdgeInsets.all(25),
          highlightColor: Colors.redAccent,
          child: Text('RaisedButton - highlight Color'),
          onPressed: () {
            //onpressed gets called when the button is tapped.
            print("RaisedButton tapped");
          },
        ),

12. Color splashColor

splash color example
splashColor property shows animation when touches the button, Like something falls into liquid.

RaisedButton(
          padding: EdgeInsets.all(100),
          splashColor: Colors.redAccent,
          child: Text('RaisedButton - Splash Color'),
          //makes background color white
          onPressed: () {
            //onpressed gets called when the button is tapped.
            print("FlatButton tapped");
          },
        ),

13. Brightness colorBrightness

brightness example - raisedbutton

If colorBrightness is Brightness.light, then text color set to Black, otherwise text color set to white.

RaisedButton(
                child: Text('RaisedButton - Brightness.light'),
                colorBrightness: Brightness.light,
                color: Colors.blue[100],
                onPressed: () {
                  //onpressed gets called when the button is tapped.
                  print("RaisedButton tapped");
                },
              ),
              RaisedButton(
                child: Text('RaisedButton - Brightness.dark'),
                colorBrightness: Brightness.dark,
                color: Colors.black,
                onPressed: () {
                  //onpressed gets called when the button is tapped.
                  print("RaisedButton tapped");
                },
              ),

14. double elevation

flutter raisedbutton elevation

By increasing elevation, you can see RaisedButton is more floating above the page and shadow spreads too.


RaisedButton(
          elevation: 5.0,
          color: Color(0xFFCE93D8),
          child: Text('RaisedButton - Elevation'),
          onPressed: () {
            //onpressed gets called when the button is tapped.
            print("RaisedButton tapped");
          },
        ),

15. double focusElevation

focuselevation example
This property used to elevate or make shadow when the RaisedButton gets focus.


         import 'package:flutter/material.dart';

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
  FocusNode _raisedFocusNode;

  @override
  void initState() {
    super.initState();
    _raisedFocusNode = FocusNode();
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "RaisedButton focusElevation Example",
      home: Scaffold(
        appBar: AppBar(
          title: Text("RaisedButton focusElevation Example"),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0),
              child: TextField(
                onChanged: (_) {
                  FocusScope.of(context).requestFocus(_raisedFocusNode);
                },
              ),
            ),
            RaisedButton(
              color: Colors.deepOrange[300],
              focusNode: _raisedFocusNode,
              focusElevation: 8.0,
              child: Text("DONE"),
              onPressed: () {},
            )
          ],
        ),
      ),
    );
  }
}


16. double hoverElevation

The hoverElevation property makes RaisedButton elevated when the pointer hovers over the RaisedButton.

17. double highlightElevation

highlight elevation

The highlightElevation property can be used to show more shadow when the RaisedButton pressed. By default, highlightElevation value is 8.0

RaisedButton(
          color: Colors.red,
          textColor: Colors.white,
          highlightElevation: 15.0,
          child: Text('RaisedButton - highlight elevation'),
          onPressed: () {
            //onpressed gets called when the button is tapped.
            print("RaisedButton tapped");
          },
        ),

18.double disabledElevation

disabledelevation raisedbutton

By default, disabled Elevation is 0.0, you can customize it using like below.

RaisedButton(
            disabledElevation: 1.0,
            child: Text("DONE"),
            onPressed: null,
          ),

19. EdgeInsetsGeometry padding

raisedbutton padding all

  • padding property used to generate space between child widget and Borders of the Parent widget. Here, RaisedButton.
  • padding property needs EdgeInsets value.
  • Here EdgeInsets.all(50) means give 50 padding to all sides of the child or Text widget.
RaisedButton(
                child: Text('RaisedButton'),
                onPressed: () {},
                padding: EdgeInsets.all(50),
                color: Color(0xFFFFAA4D),
              ),

raisedbutton padding

  • If you want to move text child to certain sides only, then you can use EdgeInsets.only()

raisedbutton top left right padding

  • You can specify more than one side.

raisedbutton symmetric padding

  • You can specify horizontal or vertical sides by applying EdgeInsets.symmetric().

20. Widget child

Just like almost other Flutter widgets, RaisedButton also gives child property to hold other widget.
Most of the time the child must be Text. But you can use others too. For example, the Image.

21. autofocus

RaisedButton’s autofocus is false by default. you can turn it on by adding autofocus:true.

22.Flutter RaisedButton Shapes Example

Shape Using Border.all()

RaisedButton(
                onPressed: () {},
                child: Text('RaisedButton'),
                shape: Border.all(
                  width: 2.0,
                  color: Color(
                    0xFF03DAC5,
                  ),
                ),
              ),

StadiumBorder

stadiumborder RaisedButton

RaisedButton(
                onPressed: () {},
                child: Text('StadiumBorder'),
                shape: StadiumBorder(),
                color: Color(
                  0xFF03DAC5,
                ),
              ),

CircleBorder

circleborder

  RaisedButton(
                onPressed: () {},
                child: Text('GO'),
                shape: CircleBorder(),
                color: Color(
                  0xFF03DAC5,
                ),
              ),

CircleBorder with BorderSide

circleborder with borderside raisedbutton

RaisedButton(
                onPressed: () {},
                child: Text('OK'),
                color: Colors.amber[100],
                shape: CircleBorder(
                  side: BorderSide(
                    color: Color(
                      0xFF03DAC5,
                    ),
                  ),
                ),
              ),

Rounded Rectangular Border

rounded rectangular border raisedbutton

RaisedButton(
                child: Text('Rounded Rectangle Border'),
                onPressed: () {},
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15)),
                color: Colors.amber[100],
              ),

Beveled Rectangular Border

beveled rectangle border

RaisedButton(
                onPressed: () {},
                child: Text('Beveled Rectangle Border'),
                shape: BeveledRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                color: Colors.amber[100],
              ),

OutlineInputBorder

outline input border

RaisedButton(
                onPressed: () {},
                child: Text('Outline Input Border'),
                shape: OutlineInputBorder(),
                color: Colors.amber[100],
              ),

UnderlineInputBorder

underline input border

RaisedButton(
                onPressed: () {},
                child: Text('Underline Input Border'),
                shape: UnderlineInputBorder(),
                color: Colors.amber[100],
              ),

How To Change Width & Height Of RaisedButton

flutter raisedbutton height width

In this example, You will change RaisedButton height and width using ButtonTheme.


Padding(
            padding: const EdgeInsets.all(8.0),
            child: ButtonTheme(
              minWidth: double.infinity,
              height: 50.0,
              child: RaisedButton(
                color: Colors.amber[300],
                onPressed: () {},
                child: Text('RaisedButton'),
              ),
            ),
          ),

  • Here ButtonTheme helps to customize RaisedButton
  • minWidth: double.infinity means minimum width must be same as parent.
  • height: 50.0
  • If you remove padding widget, RaisedButton will stretch to screen.

RaisedButton With Image Icon Example in Flutter

raisedbutton with image icon flutter


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('RaisedButton Icon Example'),
        ), 
        body: Center(
          child: RaisedButton.icon(
            onPressed: () {
              print('RaisedButton.icon clicked');
            },
            icon: Icon(Icons.attach_file), //icon image
            label: Text('Attach File'), //text to show in button
            textColor: Colors.white, //button text and icon color.
            color: Colors.red[400],
          ),
        ),
      ),
    );
  }
}



Flutter Gradient RaisedButton Example

flutter gradient raisedbutton example

Let’s make a Gradient Button…


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Gradient RaisedButton Example'),
        ),
        body: Center(
          child: RaisedButton(
            textColor: Colors.white,
            padding: EdgeInsets.all(0.0),
            shape: StadiumBorder(),
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25.0),
                gradient: LinearGradient(
                  colors: [
                    Color(0xFF00b09b),
                    Color(0xFF96c93d),
                  ],
                ),
              ),
              child: Text(
                'ANDROIDRIDE',
                style: TextStyle(fontSize: 15.0),
              ),
              padding: EdgeInsets.symmetric(horizontal: 70.0, vertical: 15.0),
            ),
            onPressed: () {
              print('Gradient RaisedButton clicked');
            },
          ),
        ),
      ),
    );
  }
}


Flutter RaisedButton Example – Data from List

flutter raisedbutton list example

In this example, you will create an application that will display items in the list using RaisedButton.

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State {

  List myList = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
  ];

  int counter = 0;//stores list index

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            'Flutter RaisedButton Example',//appbar title
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  myList[counter],//each array item
                  style: TextStyle(fontSize: 45.0),
                ),
              ),
              RaisedButton(
                color: Colors.red,
                textColor: Colors.white,
                elevation: 10.0,
                onPressed: () {
                  setState(
                    () {
                      if (counter == 6) {
                        counter = 0;
                      } else {
                        counter++;
                      }
                    },
                  );
                },
                child: const Text('Click Here'),//button label
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • Here code has one counter variable and list of weekdays.
  • Using column and Center widget, we made TextField and RaisedButton center in screen.
  • When you click on the RaisedButton, it will add counter variable by one.
  • Incrementing counter variable, shows different item in List

For more information: docs

3 Flutter FlatButton Examples With Tutorial

flutter text button flatbutton
There are many widgets in Flutter to make a better user interface. In every UI, Buttons have their own important role.

From this post, you will start to learn about the Flutter button widgets. Such as FlatButton, RaisedButton, OutlineButton, and more.

So let’s start with Flutter FlatButton.

Flutter FlatButton

flutter flatbutton
flutter flatbutton

Flat Button ??

Yes, Because by default, it’s just a black text or label without any

  • borders
  • elevation

You can use flatbutton in toolbars, dialogs, cards, and where ever enough space to add. Flatbutton also make the icon widget using FlatButton.icon().

FlatButton Simple Example

So let’s start programming and make a simple FlatButton like below. You can create flutter project using flutter command or with the help of Android Studio.

flutter flatbutton example

 

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FlatButton(
        child: Text('FlatButton'),
        color: Colors.white,
        onPressed: () {
          print("FlatButton tapped");
        },
      ),
    );
  }
}

 

  • App gets started execution from main method. At last, build() method renders FlatButton with the help of MaterialApp.
  • If you do not use the MaterialApp in above code, it could result in No directionality widget found error.
  • I have used white color as FlatButton background using the color property. Otherwise, you could get a black screen with debug banner.
  • Already told you FlatButton text color is black by default

Check it out by removing color: Colors.white line from above code and reload.

FlatButton Properties

Let’s talk about the properties of FlatButton.

flatbutton onpressed example

1. VoidCallback onPressed: It gets called when FlatButton is tapped, You need to pass VoidCallback method, means no arguments and no return value.


For ex: void myFunction();

If you haven’t provided onPressed property or specified null value, then the button will look like in the first one from the above image.

If you have given a method name or anonymous function then the button will look like in the second one.

Okay. How to provide values to onPressed property.

  1. Using anonymous function

  2. 
    FlatButton(  
                onPressed: () {
               //implement your code.
    },
               .....
     ),
    
    
  3. Using function name

  4. void flatButtonTapped(){
      
    }
    
    FlatButton(onPressed: flatButtonTapped,
    
    )
    
    

    You don’t need to give parentheses ‘()’ here. Only the function name. Download all source code from the top link.

    2. VoidCallback onLongPress
    This property gets called when a long tap occurs. Just like onPressed property, pass an anonymous function or method name.

    
    FlatButton(onLongPress: (){},
    
    

    3. ValueChanged onHighlightChanged
    flatbutton highlight changed
    onHighlightChanged calls when you click down or up the button. When the button clicks down, it gives true value. false when button clicks up.

    
    FlatButton(
                child: Text('FlatButton'),
                onHighlightChanged: (value) {
                  print('onHighlightChanged value : $value');
                },
                onPressed: () {
                  //onpressed gets called when the button is tapped.
                },
              ),
    

    4. ButtonTextTheme textTheme

    It control the button’s text color based on the theme. There are 3 values

    1. ButtonTextTheme.Normal
    2. ButtonTextTheme.accent
    3. ButtonTextTheme.primary

    you can use like this

    
    textTheme: ButtonTextTheme.normal.
    
    

    It shows color based on your theme and swatch.

    5. Color textColor

    flatbutton textcolor example

    It determines button label’s or text color.

    
    FlatButton(
                onPressed: () {},
                child: Text("Login"),
                textColor: Colors.indigo,
              ),

    6. Color disabledTextColor

    flatbutton disabled text color example

    The color is used to display when the button is disabled. set null to onPressed.

    
    FlatButton(
                    child: Text('Flat Button - Default Disabled Text Color'),
                    onPressed: null,
                  ),
                  FlatButton(
                    child: Text('Flat Button - Custom Disabled Text Color'),
                    onPressed: null,
                    disabledTextColor: Colors.black54,
                  ),

    7. Color highlightColor

    Highlight property uses to highlight the button when it pressed. After the tap event, highlightColor spreads to fill the whole button and fade out.

    flatbutton high light color

    
    FlatButton(
              padding: EdgeInsets.all(80),
              highlightColor: Colors.redAccent,
              child: Text('FlatButton - highlight Color'),
               onPressed: () {
                //onpressed gets called when the button is tapped.
                print("FlatButton tapped");
              },
            ),
    

    8. Color splashColor

    When the button tapped, splashColor or tap event behaves as something falls into the liquid.

    splash color example

    
    FlatButton(
                       child: Text('Button'),
                       onPressed: (){},
                       splashColor: Colors.red,
            )
    

    9. Brightness colorBrightness

    flatbutton brightness example

    It’s used to increase the readability of text in Button. Use Brightness.light for light and Brightness.dark for dark background color.

    
    FlatButton(
                    child: Text('FlatButton - Brightness.light'),
                    colorBrightness: Brightness.light,
                    color: Colors.limeAccent,
                    onPressed: () {
                      //onpressed gets called when the button is tapped.
                      print("flat button tapped");
                    },
                  ),
                  FlatButton(
                    child: Text('FlatButton - Brightness.dark'),
                    colorBrightness: Brightness.dark,
                    color: Colors.deepPurple,
                    onPressed: () {
                      //onpressed gets called when the button is tapped.
                      print("flat button tapped");

    10. EdgeInsetsGeometry padding
    padding property helps us to specify the padding of FlatButton internal child. Here internal child is Text widget.

    
    FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    padding: EdgeInsets.all(50),
                    color: Color(0xFFFFD8C8),
                  ),
    • EdgeInsets.all() – Give enough padding to all sides of button’s text. Above code will apply 50 padding for all sides of the Text(Top, Bottom, Left and Right).

    • EdgeInsets.only() – It gives padding to the only specified side. You can specify one or more sides like below.

    flutter padding - EdgeInsets.only(top,left, right)

    
      FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFFFC6453),
                    padding: EdgeInsets.only(top: 10, left: 30, right: 20),
                  ),
    

    • EdgeInsets.symmetric() – You can provide values in horizontal and vertical directions.
    
      FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFF534858),
                    colorBrightness: Brightness.dark,
                    padding: EdgeInsets.symmetric(horizontal: 50),
                  ),
    
                  FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFF534858),
                    colorBrightness: Brightness.dark,
                    padding: EdgeInsets.symmetric(vertical: 50),
                  ),
                  Padding(
                    padding: EdgeInsets.all(10),
                  ),
                  FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFF534858),
                    colorBrightness: Brightness.dark,
                    padding: EdgeInsets.symmetric(horizontal: 50, vertical: 30),
                  ),
    
    

    11. ShapeBorder shape

    Shape property gives different options to make different shapes of flatbutton. Let’s make a rectangle FlatButton using shape property with the help of Border.all().

    flatbutton border all shape

    FlatButton(onPressed: (){}, child: Text('OK'),
              shape: Border.all(width: 2.0, color: Colors.pink),),
    
    
    • Border width is 2.0 and color is pink.

    StadiumBorder shape

    
     FlatButton(
                    onPressed: () {},
                    child: Text('StadiumBorder'),
                    shape: StadiumBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),
    

    CircleBorder

    FlatButton(
                    onPressed: () {},
                    child: Text('OK'),
                    shape: CircleBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,)
    
    

    CircleBorder with Side

    
     FlatButton(
                    onPressed: () {},
                    child: Text('OK'),
                    shape: CircleBorder(
                      side: BorderSide(
                        color: Colors.pink,
                      ),
                    ),
                  )
    

    Rounded Rectangle Border

    FlatButton(
                    child: Text('Rounded Rectangle Border'),
                    onPressed: () {},
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15)),
                    color: Colors.pink,
                    textColor: Colors.white,
                  )
    

    Beveled Rectangle Border

    FlatButton(
                    onPressed: () {},
                    child: Text('Beveled Rectangle Border'),
                    shape: BeveledRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),

    Outline Input Border

    FlatButton(
                    onPressed: () {},
                    child: Text('Outline Input Border'),
                    shape: OutlineInputBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),

    YOu can create underline using shape.

    Underline Input Border

    flatbutton underline input border

     FlatButton(
                    onPressed: () {},
                    child: Text('Underline Input Border'),
                    shape: UnderlineInputBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),

    FlatButton.Icon Example

    FlatButton.Icon Example
    Let’s create the Icon button using FlatButton.Icon

    
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'FlatButton Icon Ex',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(title: Text('FlatButton Icon Example'),
            centerTitle: true,),//it makes appbar title to center
            body: Center(
              child: FlatButton.icon(
                icon: Icon(Icons.add_alarm),//icon image
                label: Text('Add alarm'),//text to show in button
                textColor: Colors.white,//button text and icon color.
                color: Colors.green,//button background color
                onPressed: () {},
              ),
            ),
          ),
        );
      }
    }
    
    • Provided icon and label to FlatButton.icon()

    Flutter FlatButton onPressed Example – Counter Button


    flatbutton onpressed example
    In this example, you will learn how to change count using Flutter FlatButton. Final output will be like above image. Okay, Let’s start.

    
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State {
      int counter = 0;
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('FlatButton onPressed Example'),
            ),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Center(
                  child: Text(
                    '$counter',
                    style: TextStyle(fontSize: 60.0),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                FlatButton(
                  child: Text('CHANGE COUNT'),
                  onPressed: (){
                    setState(() {
                      counter = counter + 1;
                    });
                  },
               color: Colors.red,
                  textColor: Colors.white,
                ),
              ],
            ),
          ),
        );
      }
    }
    
    
    
    • Application starts execution from main() function.
    • The build() function builds user interface.
    • when we tap on the button, it increases counter variable by 1 and also calls setState().
    • The setState() function calls build() method again.

    Assume you liked this post, please share it with your family and friends.

    More information about Flutter FlatButton: FlatButton docs

7 Flutter Commands & Command Line Options You Must Know : Create New Project, Run & More Commands Using CLI

flutter create new project command line options cli create flutter app
In this post, you will learn about flutter terminal commands and command-line options. Using Flutter command-line interface (CLI), you can perform lots of operations in your project.

Before that make sure you have downloaded Flutter SDK and updated path variable if you are using Windows.

If you haven’t, you can use Flutter Android Studio post to do that.

You could run below commands in flutter console too.

flutter console terminal

This is Flutter console. You can find it in Flutter SDK.

Let’s start…

7. Flutter clean – Reduces Project Size by deleting build and .dart_tool directories.

When I created a simple flutter app, it’s size only below 200 kb but after a run in an emulator, Its size largely increases and takes more than 300 MB.

So if you have a low-configuration PC and you are learning flutter by making different apps. That might takes lots of memory in your device.

So just use below command in the root folder of the project.

flutter clean
flutter clean
flutter clean command
  • Using “flutter clean” command, you can reduce flutter project size. The command just deletes the build directory and some other files.

6.Flutter build – List Build Commands

For publishing your flutter app, you need to make binaries for Android and Ios. The build command by default makes a release flavor of the app.

flutter build

flutter build
  • It helps to list build formats of flutter
flutter build appbundle - build an appbundle
  • Recommended to build appbundle than apk.
flutter build apk 
  • It builds fat apk.
flutter build apk --split-per-abi 
  • Above command creates apks based on ABI.
flutter build ios 
  • Creates binaries for Ios.

5. Flutter channel – List Different Flutter Source Code Branches

Flutter channel means a git branch where we get Flutter source code. It could be used to change different branches such as master, dev, beta, and stable.

Just run “flutter channel” to find out.

flu
flutter channel
  • The channel with star symbol is you are currently using.
  • Here I am using stable channel and stable is recommended for product development.

Let’s change the channel…

flutter channel [channel_name] – this is syntax, let’s change stable to master.

flutter channel master
how to change flutter channel
change flutter channel to master
  • run “flutter upgrade” to ensure you are on the latest build.

4. Flutter run – Run Flutter Project

If you have created your flutter project, then you can run it on any devices or emulators using the run command. While using the run command, it must be called from the root directory of the project. you can use cd command for that purpose.

cd flutter_app
flutter run

    • If there are no emulators and devices connected, cmd will show “No supported devices connected”.
    • The app will get loaded and start running, If single device get connected,.
    • Multiple devices get connected, specify one device id with “flutter run -d” command
flutter run & fluttter run -d
flutter run & fluttter run -d
      • Just look at the above image, I just run “flutter run” and I got two devices, emulator and a physical device.
flutter run -d emulator-5554
    • Here I use emulator-5554 as device id.
  • If you want to run app on all devices, run “flutter run -d all” command.
  • By default, the debug version of the app will run on your device. It supports hot reload and fine for testing purposes.
  • There are other build flavors you can use like profile, flavor, and release.
  • the release version is for when you ready to publish it in play store or Appstore and it is not supported for emulators.
flutter run --release
  • If you use above command, you could see that the debug banner is gone.

3.flutter create – Create new flutter project Using Command Line

This command is used to create flutter projects, such as Flutter application, package, plugin, and module.

flutter create [output_directory_name or project_name]
  • Creates a Flutter app project
flutter create flutter_app
  • Creates a flutter app named “flutter_app”.
create flutter app flutter create new project command line
flutter create new project command line
  • After running above command, necessary files will be created on the specified name.
  • project name – It’s recommended to use lowercase with underscores.
  • If you run flutter create with existing flutter project name then the project will be recreated and if there are any files is missing, that too recreated again.
flutter creates project again
flutter recreates project
  • I have deleted main.dart file in the lib folder, now it recreated.

Let’s check how to create a package using flutter commands.

flutter create -t package flutter_package
  • Creates a package named flutter_package.
flutter create package
flutter create package
  • You can use -t or –template to specify the flutter project.

Let’s create a plugin project with flutter create command.

flutter create -t plugin flutter_plugin
  • It creates plugin project named flutter_plugin.
  • By default, swift is used as ios language, Kotlin for Android.

we can change that by using the below command.

flutter create -t plugin -i objc -a java my_flutter_plugin
  • Here -i means ios language – objc used, -a means android language.
  • You can remove -t plugin, if you are making Flutter application

Let’s create a project with our own package name and description, use below code

flutter create --org com.androidride --description "simple example" my_flutter_app
  • It creates a package name with “com.androidride”, you can view description in README.md

2.Flutter doctor – Diagnoses Flutter system environment.

This command diagnoses our system and tells us is everything fine or any issues need to treat just like a doctor.

If there are no issues, you are good to go. You don’t need to worry about all issues. For example, you are making a flutter app in VS Code, So you can avoid problems associated with Android Studio.

For example, Flutter plugin not installed in Android Studio like error.

flutter doctor

flutter doctor

  • Here I have one issue because I haven’t connected any devices.

Okay… Let’s know more details by running

flutter doctor -v

flutter doctor -v

  • Using the above image, we can understand that flutter doctor -v  gave more details about our Flutter development environment and tools.

1. flutter help

Just like the name it helps developers to find other commands and tells us how to use them just like a senior developer who is sitting nearby you. So I think, you don’t need to remember all commands I told above, Just remember this one.

flutter help
  • flutter -h and flutter –help give you the same results.
flutter help command
flutter help
flutter help -v
  • The above command gives a verbose output of flutter help.
flutter help [command]
  • Using the above syntax, we can check how other commands work.
flutter help create
  • Above command helps us to know more about create command.
flutter help create
flutter help create

Flutter Other Commands

Now I will show you some other commands with fewer details that helped me while I create flutter apps.

  • flutter doctor –android-licenses – It helps to accept all android licenses.
  • flutter logs – Shows logs generated by flutter apps in emulators and devices.
  • flutter analyze – It guides to make better code.
  • flutter config – Configures Flutter SDK and other settings.
  • flutter config –android-sdk “SDK_PATH”  – set Android SDK path.
  • flutter config –android-studio-dir “ANDROID_STUDIO_DIRECTORY_LOCATION” – sets Android Studio directory location
  • flutter upgrade – upgrade Flutter SDK to latest version
  • flutter downgrade – downgrade Flutter SDK to lower version
  • flutter pug get – pub is dart’s package manager, this command installs packages. The same function as packages get in Android Studio and Get packages in VS code.
  • flutter pub upgrade – upgrade packages to the latest version.
  • flutter emulators – shows available emulators.
  • flutter devices – shows connected emulators and devices
  • flutter screenshot – Takes screenshot from emulator or device
  • flutter screenshot -o C:\Users\Admin\Desktop\screenshot.png – Takes screenshot and stores in Desktop. (Windows users)

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

How To Install Flutter In Android Studio In Windows : Flutter Android Studio Set Up Tutorial

how to install flutter in android studio in windows 10
Welcome to our first Flutter Android Studio tutorial.

Let’s start by talking about Flutter.

Google has introduced its software development kit Flutter in 2017. Using Flutter, you can develop applications for Android, ios, Mac, Windows, Linux, and More.

If you are making an app for Android and ios. You can consider using Flutter, which helps you to make both in one codebase.

So in this post, you will learn,

I am assuming that you have downloaded

and know, how to create an android project, emulator also.

How To Download Flutter SDK In Windows

how to install flutter in android studio in windows

download flutter sdk windows

  • While scrolling down, you will see a blue button with flutter latest SDK version in a zip file, just click on it.
  • Download begins…

Extract download flutter sdk windows

  • After the download, Extract the zip file

 

flutter sdk windows

  • Just cut and paste the extracted file in C drive, just like above. You can choose your suitable location except for Program Files in C drive.
  • Just click on the extracted directory.

flutter sdk

 

  • Click on flutter.

flutter console

  • This is Flutter software development kit. Here you can click on flutter console and check flutter commands.

flutter console terminal

  • This is flutter console window.
  • click on bin folder.

flutter bin directory

  • We need to update the PATH variable with “…/flutter/bin”, then only we can run flutter commands from any command prompt.
  • So copy the path with “flutter/bin” like shown above.

How To Update Path Variable With Flutter SDK Path In Windows

environment variable flutter setup

  • Search “env” on the search bar and click on “Edit environment variables for your account”.

update path variable with flutter

  • Click on the path field -> Edit -> New -> Paste it in the empty field. Just like above.
  • Click Ok.

create new path variable flutter

If the Path variable doesn’t exist, you need to create one. By clicking New->Providing values in each field (name and value) and click OK (just like shown above).

flutter doctor command check to install flutter plugin

  • Open the command prompt, and run the “flutter doctor” command.
  • If there is any problem you will see the red cross mark.
  • Here I got errors because flutter and dart plugin are unavailable, let’s clear it now.

How To Install Flutter Plugin In Android Studio

plugins android studio

  • Open Android Studio
  • If you don’t get a window like the above image.
    You may not close your last opened project. So just close your project, File -> Close Project.
  • Click on “Configure“.

plugins android studio 2

  • Next click on the “plugins” items from the drop-down menu.
  • flutter marketplace
  • Next, we have to find the flutter plugin from the marketplace. Make sure you are on the marketplace tab.
  • Then search “Flutter” in the search box and press Enter.
  • Click on the install button to install the flutter plugin.

flutter and dart plugin installation android studio

 

  • Dart plugin is also needed to make flutter applications. You don’t need to install separately. Just click on ‘Install‘ on the dialog box.
  • It will automatically download both.

restart android studio ide

  • Now click on the Restart IDE button to restart the Android Studio.

restart android studio ide dialog

  • In the next alert dialog box, “Restart Android Studio to activate changes in plugins?“. Click on Restart.

start a new flutter project in android studio

  • After the restart, now you can see “Start a new flutter project” item in the window.
  • That means you have successfully installed a flutter plugin in Android Studio.
  • But check again to confirm our system is ready to create flutter applicaions using flutter doctor command.

check flutter setup

  • Everything fine now.

How To Create Flutter Project In Android Studio

start a new flutter project in android studio

  • Click on “Start a new Flutter project”.

flutter project flutter application android studio

 

  • Select “Flutter Application” and click “Next”.

How To Change Flutter SDK Path In Android Studio

new flutter application android studio

 

  • I just let the project name as ‘flutter_app’. After that, one of the important step is to change the Flutter SDK path.
  • Click on Flutter SDK path (3 dot) button.

flutter sdk path set in android studio

  • Now you have to select the flutter SDK location, for me, it’s in C drive.  Expand drives by clicking on it.
  • After selecting flutter folder just click OK.

set flutter sdk path

  • Flutter SDK path is set now, then click Next.

change package name of flutter project

 

  • Change package name if you want.
  • I have changed to “com.androidride” , leave others, and click Finish.

How To Run Flutter Project In Android Studio

flutter run project android studio

 

  • After the build, the project will shown up just like above.
  • Like Android Project, Select your emulator and click on Run button.

run flutter app

  • The flutter application is ready now.

How To Open Existing Flutter Project In Android Studio

Method I – Drag And Drop Flutter Project To Android Studio

open existing flutter project in android studio

 

  • Before drag and drop your project, make sure you have installed the flutter plugin in Android Studio.

Method II – Using Open An Existing Android Studio Project

open existing flutter project in android studio

 

  • Click on “Open an Existing Android Studio project “.

open existing flutter app

  • Now you have to find the location of your flutter project. Here, my fluter project is located at desktop.
  • After selecting your project, just click OK.
  • The project is ready now.

I believe that this post will help you start your flutter journey. If you like this post, please share it with your family and friends. Thank you.

3 Android RecyclerView Load More On Scroll Examples

android recyclerview load more on scroll example

We are using lots of apps that load data while we scrolling. Facebook, Instagram, and more apps using this technique. This technique helps users to wait less time.

So if you are planning to make an app like that, using RecyclerView. Then this post is for you.

In this post, You will learn how to use Load More on Scroll or pagination or endless scrolling or infinite scroll or whatever you call, with RecyclerView.

Before that, I recommend reading our RecyclerView Tutorial Guide.

This post is not dealing with the pagination library.

How To Implement Pagination In Android RecyclerView

In this post, I am going to talk about two methods, that implement pagination in RecyclerView. But in both methods, we will use scroll Listener with RecyclerView to listen to scroll events. When RecyclerView scrolls, onScrolled() method gets called.

So first learn how to add OnScrollListener with Recyclerview.

How To Add OnScrollListener With RecyclerView


    //attaches scrollListener with RecyclerView
        recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
        {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
            {
                super.onScrolled(recyclerView, dx, dy)

              

            }
            })


Simple Android RecyclerView Load More On Scroll Example

Let’s make a linear list Using RecyclerView and add an endless scroll feature.

pagination in android recyclerview

After the implementation of scroll listener, we should do the following

  • we use findLastCompletelyVisibleItemPosition() to get the position of last visible item.
  • Use a variable which checks progressbar loading or not
  • If last item reached and progressbar not loading, loadmore() gets called. Using Handler, we add “load” in list.
  • When adapter checks list, ProgressBar gets added.
  • Next data chunks received, ProgressBar gets removed and data got added.
  • For showing different View types. here
    1. Data row
    2. ProgressBar

    Make use of getViewType() method in RecyclerView.Adapter.

MainActivity.kt

class MainActivity : AppCompatActivity()
{
    //handler instance
    var handler: Handler = Handler()
    //list for holding data
    lateinit var list : ArrayList

    lateinit var adapter : RecyclerViewAdapter
    //Variable for checking progressbar loading or not
    private var isLoading: Boolean = false
    lateinit var layoutManager : LinearLayoutManager



    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        layoutManager = LinearLayoutManager(this)
        //attaches LinearLayoutManager with RecyclerView
        recyclerview.layoutManager = layoutManager

        list = ArrayList()

        load()

        adapter = RecyclerViewAdapter(list)

        recyclerview.adapter = adapter

        addScrollerListener()

    }

    private fun addScrollerListener()
    {
        //attaches scrollListener with RecyclerView
        recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
        {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
            {
                super.onScrolled(recyclerView, dx, dy)

                if (!isLoading)
                {
                    //findLastCompletelyVisibleItemPostition() returns position of last fully visible view.
                    ////It checks, fully visible view is the last one.
                    if (layoutManager.findLastCompletelyVisibleItemPosition() == list.size - 1)
                    {

                        loadMore()
                        isLoading = true

                    }
                }

            }
            })
    }

    private fun loadMore()
    {
        //notify adapter using Handler.post() or RecyclerView.post()
        handler.post(Runnable
        {
            list.add("load")
            adapter.notifyItemInserted(list.size - 1)

        })

        handler.postDelayed(Runnable {

            //removes "load".
            list.removeAt(list.size - 1)
            var listSize = list.size

            adapter.notifyItemRemoved(listSize)
            //sets next limit
            var nextLimit = listSize + 10

            for(i in listSize until nextLimit)
            {
                list.add("Item No $i")
            }

            adapter.notifyDataSetChanged()
            isLoading = false

        },2500)
    }


    private fun load()
    {
        for(i in 0..9)
        {
            list.add("Item No: $i")
        }
    }

}

 

  • It's better to use Handler.post() or RecyclerView.post() while updating adapter when RecyclerView measures.
  • findLastCompletelyVisibleItemPosition() returns only completely visible Item's position, So make sure your last view is fully visible.
  • 2500 milliseconds - delay time

RecyclerViewAdapter.kt

package m.example.simplerecyclerviewloadmoreex_kotlin

import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.row.view.*

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.lang.IllegalArgumentException

class RecyclerViewAdapter(var list: ArrayList<String>) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
{
    companion object
    {
        private const val VIEW_TYPE_DATA = 0;
        private const val VIEW_TYPE_PROGRESS = 1;
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewtype: Int): RecyclerView.ViewHolder
    {
        return when (viewtype)
        {
            VIEW_TYPE_DATA ->
            {//inflates row layout
                val view = LayoutInflater.from(parent.context).inflate(R.layout.row,parent,false)
                DataViewHolder(view)
            }

            VIEW_TYPE_PROGRESS ->
            {//inflates progressbar layout
                val view = LayoutInflater.from(parent.context).inflate(R.layout.progressbar,parent,false)
                ProgressViewHolder(view)
            }
            else -> throw IllegalArgumentException("Different View type")

        }
    }

    override fun getItemCount(): Int
    {
        return list.size
    }

    override fun getItemViewType(position: Int): Int
    {
        var viewtype = list.get(position)

        return when(viewtype)
        {//if data is load, returns PROGRESSBAR viewtype.
            "load"  -> VIEW_TYPE_PROGRESS
            else -> VIEW_TYPE_DATA
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, p1: Int)
    {

        if (holder is DataViewHolder)
        {
            holder.textview.text = list.get(p1)
        }
    }

    inner class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    {
        var textview = itemView.textview

        init {
            itemView.setOnClickListener {
                Toast.makeText(itemView.context,list.get(adapterPosition),Toast.LENGTH_LONG).show()
            }
        }
    }

    inner class ProgressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

}

 

  • getItemViewType(int position) method returns VIEW_TYPE_PROGRESS, if data is "load". Otherwise, it returns VIEW_TYPE_DATA.
  • Based on ViewType, In onCreateViewHolder layout will get inflated.

Grid RecyclerView Pagination Example - Different Approach

Now we will make a Grid RecyclerView with pagination. Sometimes we need to load data before the last item loads.

grid android recyclerview infinite scroll example pagination

For that purpose, you can make use of this approach.

Okay, what we do in this approach.

we define 3 variables, visibleThreshold, lastVisibleItem, and totalItemCount.

  • visibleThreshold : limit of items that user want to see before loading next items
  • lastVisibleItem : just like name, last visible item position in adapter
  • totalItemCount : No.of items in adapter

after the scroll listener setup,

  • When onScrolled() gets called, just checks totalItemCount <= lastVisibleItem + visibleThreshold with isLoading : variable for storing progressbar state.
  • if both are true, next chunks of data get loaded
class MainActivity : AppCompatActivity()
{
    lateinit var list : ArrayList
    lateinit var adapter : RecyclerViewAdapter
    private var isLoading: Boolean = false
    lateinit var gridlayoutManager : GridLayoutManager


    private var visibleThreshold = 5
    private var lastVisibleItem = 0
    private var totalItemCount = 0

    //handler instance
    private var handler: Handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //no of columns or span in the grid.
        var columns = 2

        gridlayoutManager = GridLayoutManager(this, columns)
        recyclerview.layoutManager = gridlayoutManager

        load()

        adapter = RecyclerViewAdapter(list)

        recyclerview.adapter = adapter

        addScrollerListener()

        gridlayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup()
        {
            //Each item occupies 1 span by default.
            override fun getSpanSize(p0: Int): Int
            {
                return when (adapter.getItemViewType(p0))
                {
                    //returns total no of spans, to occupy full sapce for progressbar
                    RecyclerViewAdapter.VIEW_TYPE_PROGRESS -> gridlayoutManager.spanCount
                    RecyclerViewAdapter.VIEW_TYPE_DATA -> 1
                    else -> -1
                }
            }
        }
    }

      private  fun addScrollerListener()
        {
            recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
            {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
                {
                    super.onScrolled(recyclerView, dx, dy)

                    //total no. of items
                    totalItemCount = gridlayoutManager.itemCount
                    //last visible item position
                    lastVisibleItem = gridlayoutManager.findLastCompletelyVisibleItemPosition()

                    if(!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold))
                    {
                        loadMore()
                        isLoading = true
                    }
                }
            })
        }



    private fun loadMore()
    {
        handler.post(Runnable
        {
            //adds load item in list
            list.add("load")
            adapter.notifyItemInserted(list.size - 1)

        })

        recyclerview.postDelayed(Runnable {

            //removes load item in list.
            list.removeAt(list.size - 1)
            var listSize = list.size

            adapter.notifyItemRemoved(listSize)
            //next limit
            var nextLimit = listSize + 10

            for(i in listSize until nextLimit)
            {
                list.add("Item No $i")
            }

            adapter.notifyDataSetChanged()
            isLoading = false

        },7000)

    }

    private fun load()
    {
        list = ArrayList()

        for(i in 0..9)
        {
            list.add("Item $i")
        }
    }

}

  • Make ProgressBar width to maximum using setSpanSizeLookup() method

 

RecyclerViewAdapter.kt

 

class RecyclerViewAdapter(var list: ArrayList<String>) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
{
    companion object
    {
        const val VIEW_TYPE_DATA = 0;
        const val VIEW_TYPE_PROGRESS = 1;
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewtype: Int): RecyclerView.ViewHolder
    {
        return when (viewtype)
        {
            VIEW_TYPE_DATA ->
            {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.row,parent,false)
                DataViewHolder(view)
            }

            VIEW_TYPE_PROGRESS ->
            {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.progressbar,parent,false)
                ProgressViewHolder(view)
            }
            else -> throw IllegalArgumentException("Different View type")

        }
    }

    override fun getItemCount(): Int
    {
        return list.size
    }

    override fun getItemViewType(position: Int): Int
    {
        var viewtype = list.get(position)
        return when(viewtype)
        {
            "load"  -> VIEW_TYPE_PROGRESS
            else -> VIEW_TYPE_DATA
        }
    }

    override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int)
    {

        if (p0 is DataViewHolder)
        {
            p0.textview.text = list.get(p1)
        }
    }

    inner class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    {
        var textview = itemView.textview

        init {
            itemView.setOnClickListener {
                Toast.makeText(itemView.context,list.get(adapterPosition),Toast.LENGTH_LONG).show()
            }
        }
    }

    inner class ProgressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    
}

Retrofit Android RecyclerView Infinite Scroll Example

In this example, we will load data from the internet using Retrofit2. You can download PHP(data.php) code from the Source Code link shown at the top.

I am using Android Studio 3.5.


Let's create a project.

In choosing your project window, click on "Empty Activity" and click Next.

Name: RetrofitRecyclerViewLoadMoreEx

Package name: androidride.com

Select language Kotlin

I am going to use AndroidX library, so make sure you tick on the androidx.* artifacts.
That's your choice, but I recommend to use this one.

Click "Finish".


add below dependencies

implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
  • Gson converter : It helps to serialize and deserialize JSON data.

build.gradle(Module:App)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.androidride.retrofitrecyclerviewloadmoreex"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


    implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'

}

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
</resources>

 

strings.xml

<resources>
    <string name="app_name">Retrofit RecyclerView LoadMore Ex - Kotlin</string>
</resources>

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

 

  • Don't forget to add INTERNET permission in AndroidManifest.xml like below

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.androidride.retrofitrecyclerviewloadmoreex">

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

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

Data.kt

package com.androidride.retrofitrecyclerviewloadmoreex

data class Data(var category: String)
{
    var title: String? = null
    var subtitle: String? = null

    init {
        this.category = category
    }
}

DataApi.kt

package com.androidride.retrofitrecyclerviewloadmoreex

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface DataApi
{
@GET("data.php")
fun getData(@Query("index") index : Int): Call<List<Data>>
}
  • In Retrofit2, endpoints defined in Interface with special annotations.
  • This endpoint returns List.

MainActivity.kt

package com.androidride.retrofitrecyclerviewloadmoreex

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit


class MainActivity : AppCompatActivity()
{
    lateinit var list: ArrayList
    lateinit var adapter: RecyclerViewAdapter

    var notLoading = true
    lateinit var layoutManager: LinearLayoutManager
    lateinit var api: DataApi
    lateinit var retrofit: Retrofit


    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        list = ArrayList()
        adapter = RecyclerViewAdapter(list)
        recyclerview.setHasFixedSize(true)

        layoutManager = LinearLayoutManager(this)
        recyclerview.layoutManager = layoutManager
        recyclerview.adapter = adapter

        retrofit = RetrofitInstance.getRetrofitInstance()
        api = retrofit.create(DataApi::class.java)

        load(0)

        addscrolllistener()
    }

    private fun addscrolllistener()
    {
        recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
        {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
            {
                if(notLoading &&  layoutManager.findLastCompletelyVisibleItemPosition() == list.size -1 )
                {
                    list.add(Data("progress"))
                    adapter.notifyItemInserted(list.size - 1)
                    notLoading = false

                    val call: Call<List> = api.getData(list.size - 1)

                    call.enqueue( object :  Callback<List>
                    {
                        override fun onResponse(call: Call<List>?, response: Response<List>?)
                        {
                        list.removeAt(list.size - 1)
                        adapter.notifyItemRemoved(list.size)

                                if(response!!.body().isNotEmpty())
                                {
                                    list.addAll(response.body())
                                    adapter.notifyDataSetChanged()
                                    notLoading = true
                                }
                                else
                                {
                                    Toast.makeText(applicationContext,"End of data reached", Toast.LENGTH_LONG).show()
                                }

                        }

                        override fun onFailure(call: Call<List>?, t: Throwable?) {
                            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                        }
                    })
                }
            }
        })
    }

    private fun load(i: Int)
    {
        val call: Call<List> = api.getData(0)

        call.enqueue(object : Callback<List>
        {
            override fun onResponse(call: Call<List>?, response: Response<List>?)
            {
                if(response!!.isSuccessful)
                {
                    list.addAll(response!!.body())
                    adapter.notifyDataSetChanged()
                }

            }

            override fun onFailure(call: Call<List>?, t: Throwable?)
            {

            }
        })

    }
}


RetrofitInstance.kt

package com.androidride.retrofitrecyclerviewloadmoreex

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RetrofitInstance
{
    companion object
    {
        fun getRetrofitInstance(): Retrofit
        {
            val retrofit = Retrofit.Builder().baseUrl("https://www.androidride.com/").addConverterFactory(
                GsonConverterFactory.create()).build()

            return retrofit

        }
    }
}

  • For performing network requests, we need to create Retrofit Instance using Retrofit.Builder() using Base Url

RecyclerViewAdapter.kt

package com.androidride.retrofitrecyclerviewloadmoreex;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class RecyclerViewAdapter extends RecyclerView.Adapter
{

    public static final int TYPE_DATA = 0;
    public static final int TYPE_PROGRESS = 1;

    ArrayList list;

        public RecyclerViewAdapter(Context context,ArrayList list)
        {
            this.list = list;
        }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

            if(viewType == TYPE_DATA)
            {
                return new DataHolder(inflater.inflate(R.layout.row,parent,false));
            }
            else
            {
                return new ProgressHolder(inflater.inflate(R.layout.progressbar,parent,false));
            }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position)
    {
            if(holder instanceof  DataHolder)
            {
                ((DataHolder) holder).textTitle.setText(list.get(position).title);
                ((DataHolder) holder).textSubtitle.setText(list.get(position).subtitle);
            }
    }

    @Override
    public int getItemCount()
    {
        return list ==  null ? 0 : list.size() ;
    }

    @Override
    public int getItemViewType(int position)
    {
        if(list.get(position).category.equals("data"))
        {
            return TYPE_DATA;
        }
        else
         {
            return TYPE_PROGRESS;
         }
    }

    class DataHolder extends RecyclerView.ViewHolder
    {
        TextView textTitle,textSubtitle;

        public DataHolder(@NonNull final View itemView)
        {
            super(itemView);

            textTitle =(TextView)itemView.findViewById(R.id.title);
            textSubtitle = (TextView)itemView.findViewById(R.id.subtitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    Toast.makeText(itemView.getContext(),"Clicked Item: "+list.get(getAdapterPosition()).subtitle,Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    class ProgressHolder extends RecyclerView.ViewHolder
    {
        public ProgressHolder(@NonNull View itemView)
        {
            super(itemView);
        }
    }
}


retrofit android recyclerview pagination example

Thanks for scrolling. If you have liked this post, please share it with your friends and family.

3 Reasons To Buy Head First Android Development – 2nd Edition

head first android development download

Do you want to learn, how to develop Android apps?

There’s only one way – write a lot of code! : Head First Android Development.

So in this post, I am talking about Head First Android Development – 2nd Edition, One of my favorite Android programming books. Actually the 3 reasons why I think it’s better to buy and also something you want to consider before buying.

So let’s start… and find out the reasons…

Check out other’s reviews, ratings and price by clicking below “View on Amazon” link.

    • It’s the Second Edition

By referring Second Edition you can understand that there is a successful First edition. After the victorious initial release in 2015, it got positive reviews all over the world. Experienced programmers and writers Dawn Griffiths and David Griffiths made the second part as well as the first version.

They included lots of basics stuff again. Such as Constraint layout, Support library, and RecyclerView – the book becomes a larger one and it pays off.

  • It’s From Head First – This Is Enough

Head First – For me, This one reason is enough to buy this book. Not only this book fan, but I am also a Head First fan too.

One minute if you don’t know about the Head First, it’s just a book series published by Oreilly. Head First released lots of books on topics like programming, Science and Mathematics.

Okay… But what makes Head First different from others?.

Because of their teaching style.

They prefer visual learning, The brain processes visual information 60,000 times faster than text and that helps you to grasp information easily.

Visual information holds in your memory better than large chunks of text.

Saying things repetitively in different ways that also attach the information in your head.

The next one I think is conversational style – they present information just like in a conversation. Because we pay more attention to the conversation than a lecture.

Head First books are not for read-only. You have to think, write and do challenges such as puzzles, quizzes and more.

However, in their way, they tried their maximum to tune our brain with humor and excitement with knowledge in each book I have read.

  • Step By Step App Making Process Makes You More Confident

Confidence – that’s my third reason why I recommend it. When you complete Head First Android Development, you will have the confidence to make your own apps. That’s how I did feel after finished.

The chapters in the book deal with creating a new app with a new concept or updating the existing one. Whatever you do, you will write a lot of code throughout the book. Remember the beginning?

Step by step you will learn to make more apps and more about Android.

In each chapter, difficulty level increases. But you won’t feel it as much as other books when compared to this one.

Okay. Let’s talk about the chapters, how it works for you?

The book starts with creating a basic Helloworld app, in that chapter you will learn how to set up Android Development Environment and a little about other basic building blocks of Android.

After that, you start to make an interactive app built by mainly Spinner and Button in the second chapter.

In the third chapter, you will learn how to use intents with activities inside your app and other apps.

After that, chapter 4, you will learn about how activities work? What happens or which method gets called in its lifecycle with the help of a stopwatch app.

Thenceforth in Views and ViewGroups chapter, you will get to know how to use GUI components and show you how LinearLayout and FrameLayout works.

How to make complex layouts using Constraint layout that will be learned in chapter 6 by making the “My Constraint Layout” app.

If you are a beginner and have a great idea for an app, the next chapter will help you to organize your ideas and make an awesome app. For example, you will make a starbuzz app from scratch.

Following this, you will understand the importance of the Android Support library, also learn how to make shortcuts in the app bar.

Android apps are running on different devices. What you do if you want your app to look different depending on the phone or tablet? There are 3 main chapters for dealing with that question with Fragments.

You will create a workout app that’s enough to deal with fragment lifecycle methods. The next chapter will help you to implement material design in-app with the help of Android Design Support Library.

You will see how to use tabs, toolbar, floating action buttons and snack bars.

In the 13th chapter, you will learn about an advanced type of list: RecyclerView. CardView also get introduced. You will build an app with these too.

The next chapter will show you how to show different sections of our app using navigation drawer.

The next 3 chapters will clear almost all your doubts about the SQLite database in Android. Only through making apps.

after that, you will get introduced to Services, which helps us to work in the background. such as downloading files.

oh, this is enough, I have almost summarized it. But the books contain a lot more than that.

  • Before Buying Head First Android Development – Second Edition

This book is enough for a beginner, but there is something you must consider while buying this one.

      1. You should know Java programming language
      2. This is not a reference book and it takes time to complete. Just reading isn’t the way to use this book.
      3. Second edition released in 2017, so Book uses Android Studio 2.3. So it little bit outdated now.
      4. It just introduces below topics, not a detailed tutorial
        • WebView – Don’t worry, our webview guide is here
        • Content Provider
        • Loaders
        • Broadcast Receivers
        • Testing like topics.

For Indian users, All Indian Reprints of O’Reilly are printed in Greyscale (B/W)

Conclusion

There are lots of books you can find about Android Programming. For me, Head First Android Programming – Second Edition will stay in front of them. When I started learning Android app development, I always roam around online tutorials and gets nowhere. But after reading Head First, It’s changed. It gives me enough information and confidence to make my own apps. Although it’s late to review this book, but still people searching about this book, talking about this. That’s why I reviewed it now. But for beginners, It’s still worth reading. If Head First releases the 3rd edition, I would definitely read it.

4 Ideas To Create Horizontal RecyclerView With Example

horizontal recyclerview android example
Do you want to make Horizontal RecyclerView?

Before jumping into tutorial, I would recommend reading RecyclerView In Android : The Ultimate Guide.

In this post, I will teach you how to make Horizontal RecyclerView In Android with 4 ideas. In the end, we will create a Horizontal RecyclerView project too.

Okay… Let’s start.

RecyclerView uses LayoutManager class to arrange its items, so below we are going to use the LayoutManager class to make it work.

1. Horizontal RecyclerView Using LinearLayoutManager

This is the first and most commonly used option to make Horizontal RecyclerView. LinearLayoutManager provides a constructor that we can change the orientation of RecyclerView.

LinearLayoutManager(Context context, int orientation, boolean reverseLayout)

val layoutManager = LinearLayoutManager(this@MainActivity,LinearLayoutManager.HORIZONTAL,false)
recyclerview.layoutManager = layoutManager

  • Here, we use “this” because RecyclerView uses in MainActivity. If you are using RecyclerView in fragment, you can use getActivity()
  • false : Do not reverse the layout.

2.Horizontal RecyclerView Using app:LayoutManager attribute





  • app:layoutManager=”androidx.recyclerview.widget.LinearLayoutManager”: sets LayoutManger for RecyclerView.
  • android:orientation=”horizontal” : Render RecyclerView in Horizontal.
  • For support library users, Use this app:layoutManager=”android.support.v7.widget.LinearLayoutManager”.

3. Horizontal RecyclerView Using GridLayoutManager

In this part, we use GridLayoutManager for creating horizontal RecyclerView. Use the below one.

GridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout)

spanCount: Number of rows or columns based on orientation.

  val gridLayoutManager = GridLayoutManager(this@MainActivity,1,GridLayoutManager.HORIZONTAL,false)
        recyclerview.layoutManager = gridLayoutManager


You can use XML way, just like below:

    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    android:orientation="horizontal"
    app:spanCount="1"

  • For support library users, app:layoutManager=”android.support.v7.widget.GridLayoutManager”

4. Horizontal Recyclerview Using StaggeredGridLayoutManager

In this section we can use StaggeredGridLayoutManager constructor, shown below:

StaggeredGridLayoutManager(int spanCount, int orientation)

 val staggeredGridLayoutManager = StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL)
        recyclerview.layoutManager = staggeredGridLayoutManager


In XML way

app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
android:orientation="horizontal"
app:spanCount="1"

  • For support library users, Use app:layoutManager=”android.support.v7.widget.StaggeredGridLayoutManager”/li>

.

Horizontal RecyclerView In Android – Main Example

Let’s create a horizontal RecyclerView…

Just like below

Horizontal RecyclerView Android Example

Open Android Studio and start a new Android Studio project.

Application name : Horizontal RecyclerView Android Example.

Company domain: androidride.com

Check to include Kotlin support.


Select minimum SDK:API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

If you are using the latest Android Studio versions, there will be a CheckBox with the text “Use androidx.* artifacts”. Make sure that’s checked, which creates our project with androidx library.
Click Finish.

build.gradle


apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.0"
    defaultConfig {
        applicationId "com.androidride.horizontalrecyclerviewandroidexample"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'


}

colors.xml



    #008577
    #00574B
    #D81B60


strings.xml


    Horizontal RecyclerView Android Example

styles.xml



    
    

 


activity_main.xml



        

        

        


MainActivity.kt

class MainActivity : AppCompatActivity()
{
    val dataList = ArrayList()

    lateinit var adapter : RecyclerViewAdapter

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setupdata()

        adapter = RecyclerViewAdapter(dataList)


        //Using LinearLayoutManager

        val layoutManager = LinearLayoutManager(this@MainActivity,LinearLayoutManager.HORIZONTAL,false)
        recyclerview.layoutManager = layoutManager



        /*Horizontal RecyclerView using GridLayoutManager

        val gridLayoutManager = GridLayoutManager(this@MainActivity,1,GridLayoutManager.HORIZONTAL,false)
        recyclerview.layoutManager = gridLayoutManager

        */


        /*
            Horizontal RecyclerView using StaggeredGridLayoutManager

        val staggeredGridLayoutManager = StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL)
        recyclerview.layoutManager = staggeredGridLayoutManager

         */

        recyclerview.adapter = adapter
    }


    private fun setupdata()
    {
        dataList.add("ONE")
        dataList.add("TWO")
        dataList.add("THREE")
        dataList.add("FOUR")
        dataList.add("FIVE")
        dataList.add("SIX")
        dataList.add("SEVEN")
        dataList.add("EIGHT")
        dataList.add("NINE")
        dataList.add("TEN")
    }
}


item.xml






RecyclerViewAdapter.kt

class RecyclerViewAdapter(val dataList: ArrayList):RecyclerView.Adapter()
{

        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
        {
            val textview = itemView.textview
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
    {
            val inflater = LayoutInflater.from(parent.context)
            val view = inflater.inflate(R.layout.item,parent,false)

            return ViewHolder(view)
    }

    override fun getItemCount(): Int
    {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int)
    {
        holder.textview.text = dataList.get(position)
    }
}


Let’s run it and please share it with your friends, family, and co-workers.

RecyclerView With CheckBox In Android Example: 2 Examples And Tutorial About RecyclerView Adapter, Difference Between ListView & RecyclerView, and OnClickListener Will Help You To Know RecyclerView Better.

Android Recyclerview Simple Tutorial

RecyclerView??? Is that a View? What does it do?

How to use this one?

are these thoughts running through your head? then Go on.
Or
you know something about RecyclerView then Refresh your knowledge by reading this post.

In this article, you will learn about RecyclerView, RecyclerView Adapter, and a simple example that helps you to create your one.
At last, I will teach you how to use Checkbox with RecyclerView. Yes, you can scroll fearlessly without thinking about losing the selected states in CheckBox.

So fasten your seatbelts, let’s take-off now.

What Is RecyclerView In Android?

From the name, we can understand that it’s an Android View. Actually, It is a ViewGroup with scroll ability which works based on adapter principles.

In simple words, It helps us to show a large no. of data collections just like ListView and GridView.

If RecyclerView wants to show large no.of items, it does not create the same amount of views. It just creates the viewholders which hold the inflated view needed to fill the screen and some more.

After that when the user scrolls, it makes use of cached views. Yes, It recycles views, again and again, that’s why it got the name “RecyclerView”.

As a successor, It is far away from ancestors(ListView, GridView) by performances and abilities. By more features, it becomes a little bit complex too.

Let’s look up the history, ListView has been part of Android since 1.0, but each os releases, new features got added. Not in the case of ListView.

ListView simply defeated by developer’s needs such as different types of layouts and animation support. That’s where RecyclerView was born.

Finally in 2014 Android Lolipop introduced RecyclerView as a standalone support library.

After the arrival of the AndroidX library (after API level 28.0.0), RecyclerView changed its package name android.support.v7.widget.RecyclerView to androidx.recyclerview.widget.RecyclerView.

If you are using Android Studio, just add it to gradle and use.

8 Differences Between ListView And RecyclerView In Android

differences between listview and recyclerview in android

1. ViewHolder pattern
ViewHolder pattern is a strategy used to store view references in memory.

It reduces the number of calls to complicated and tedious findViewById(), which makes scrolling smooth.
,
In the case of ListView, it was optional, you can build your favorite list without any use of ViewHolder.

But when it comes to RecyclerView side, google developers make it as default for RecyclerView.

2. Re-Using views
Both ListView and RecyclerView support Reusing views. On the ListView side, it gives the option to reuse.

It’s the developer, who needs to take the action.

@Override
    public View getView(int position, View convertView, ViewGroup parent) 
{
     if(convertView == null)
     {
      //inflate your layout
     }
     //reuse convertView

}

Using the above example code, we can check the convertView is null or not. If it is null, that means there is no recycled view. Then we can inflate the layout.

If it is not null, means that not the first time, so we can use convertView and avoid layout inflation.

3. Layout Types

With ListView, you can easily make a list with simple and less code.

Code is a bit complex with RecyclerView, but it provides more options: horizontal, vertical list, grid, and staggered grid

You can also create your custom layout manager using RecyclerView.LayoutManager.

4.Animation Support

In the animation section, RecyclerView is far ahead from ListView. It’s not easy for beginners to make animations in ListView.

But RecyclerView shows Fade in, Fade out, translate and crossfade animations when you add, delete, move and update an item in RecyclerView.

This is default in RecyclerView because it internally uses the DefaultItemAnimator class. That’s why they gave that name.

If you don’t like these animations and want to make your animations make use of RecyclerView.ItemAnimator class.

5. Divider

ListView has divider by default.

The android:divider and android:dividerHeight attributes or setDivider(),setDividerHeight() helps you to make custom divider in ListView.

But RecyclerView doesn’t give these options.

But you can use the DividerItemDecoration class to make a simple divider or Make use of RecyclerView.OnItemDecoration class to decorate the view.

6. Click Events

One of the main disadvantages we face with RecyclerView is that it lacks OnItemClickListener. Because it’s not a subclass of AdapterView like ListView.

It provides RecyclerView.OnItemTouchListener to capture click events. It gives more control to the developer.

You can also use OnClickListener with views on the item.

7.Notify Methods
When notifying adapter, while data change occurs we can call notifyDatasetChanged() with ListView.

But ListView doesn’t know what had happened? It can be the addition, deletion or change of items in the dataset but don’t know what was happened.

For RecyclerView there are lots of notify* methods to inform, including notifyDatasetChanged().

Using the appropriate notify* method can invoke better animation in RecyclerView.

8. Header and Footer
It is easy to add Header and Footer in ListView using addHeaderView() and addFooterView().

But RecyclerView doesn’t have these methods instead it supports different types of view.

Finally, RecyclerView supports Nested Scrolling.

I think that’s enough for the comparison. So use them based on your needs. If you are a beginner in Android App Development, Learn ListView first then go with RecyclerView.

How To Use RecyclerView In Android?

RecyclerView is one of the most valuable widgets in Android development. Out of the box, RecyclerView is lazy. Because it has given responsibilities to different classes.

So before Using RecyclerView, you should know about these classes.

1)RecyclerView.Adapter

This is the most important class in RecyclerView. Same as other AdapterView, It connects the View(RecyclerView) and data.

RecyclerView has no default adapters, So you need to create a custom class by extending Recyclerview.Adapter.

It is responsible for

  • Creating ViewHolders
  • Binds data to ViewHolders.
  • Informs Recyclerview about dataset changes.

Most of the important methods in this class are:
i)OnCreateViewHolder() : This method is called when RecyclerView needed to create a viewholder.
ii)OnBindViewHolder(): Calls whenever needed to bind data with view in viewholder.
iii)getItemCount() : Used to return total number of items in the dataset (ArrayList, array etc).
iv)getItemViewType(): it returns the viewtype based on the position.

2) RecyclerView.LayoutManager

As the name says, it helps RecyclerView to manage layout by positioning each item.

Unlike ListView, RecyclerView shows child items in Horizontal, Vertical list, grid, and staggered grid because of LayoutManager.

Scrolling responsibility is also own by LayoutManager. When you scroll up in RecyclerView, LayoutManager moves your items up.
staggeredgridlayoutmanager gridlayoutmanager
It provides different classes for arranging items:

i)LinearLayoutManager: Creates vertical and horizontal lists.
ii)GridLayoutManager: Creates grid layouts.
iii)StaggeredGridLayoutManager: Creates StaggeredGrid layouts.
iv)WearableLinearLayoutManager: This class is for wearable devices.

3) RecyclerView.ItemDecoration

The name implies, it decorates RecyclerView’s item or view. It provides not only a divider, Using this abstract class you can draw four sides of the item. When using the divider as a view in XML, it decreases performance. That’s where the importance of this class comes through.

Version 25.1.0 Support library introduces the DividerItemDecoration class, to make a simple divider. Use addItemDecoration() method to add with RecyclerView. This class supports both horizontal and vertical orientations, so you can use it with any of your lists without any worries.

4) RecyclerView.ItemAnimator

Google developers gave more importance to animations in RecyclerView, So RecyclerView provides RecyclerView.ItemAnimator class for handling animations.

You can make custom animations using this class.

Just I said in ListView vs RecyclerView comparison, RecyclerView animates items when item adds, delete or any other move event happens because it internally uses DefaultItemAnimator.

But you can not see these animations when RecyclerView loading for the first time.

5) RecyclerView.ViewHolder
Android RecyclerView ViewHolder
You can consider ViewHolder as something which holds View.

Unlike ListView, we need to make custom ViewHolder class by extending RecyclerView.ViewHolder class.

In this subclass, we must store the item view’s references. This ViewHolder class contains additional information like its position in the layout.

Simple RecyclerView Example With CardView In Android Studio – OnClickListener Included


In this example, I will explain how to create RecyclerView in Android Studio in 10 simple steps with a detailed explanation. The final output will look like below.

Simple RecyclerView With  CardView Example In Android Studio
I assume that you have created a Project in Android Studio, then add these

STEP 1 – Add Dependencies In build.gradle

RecyclerView and CardView are support libraries, so you must add dependencies in your build.gradle file, If your app needs to support above API 28.0.0, you must use AndroidX libraries. otherwise, you can continue with the support library.

 
/* androidx library*/

    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

/*
support library
 
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
*/

STEP 2 – Import RecyclerView In Android Studio

Just like ListView, just add it to your layout. here activity_main.xml





This code creates a RecyclerView widget with id “recyclerview”.

  • android:scrollbars=”vertical” – It creates vertical scrollbar to the RecyclerView. Otherwise user never get to know how long the RecyclerView is.
  • Use android.support.v7.widget.RecyclerView as root widget if you are using the support library, attributes are same as above.

STEP 3 – Create Row Layout For RecyclerView

In this step, we will create a layout and RecyclerView will show it as child items. Right-click on the layout folder in res directory. New->Layout Resource File-> put file name as row_layout.xml and put below code.


    



  • This code creates TextView inside CardView. You can use app: namespace to specify support library attributes.
  • if you are using support library, Use android.support.v7.widget.CardView.

STEP 4 – Create An Array And Pass It To RecyclerView Adapter

RecyclerView adapter needs data and layout. So here, we will create an array of months and pass it to the adapter class, which you are going to make in the next step.

class MainActivity : AppCompatActivity()
{

    var months_array = arrayOf("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER")

    lateinit var adapter :RecyclerViewAdapter

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        adapter = RecyclerViewAdapter(months_array)
        
    }
}

  • Creates an array of months
  • lateinit: It is used to create properties that can not initialized at first. It says to the compiler that, it will initialize later.
  • Creates adapter reference and passed the array to adapter class that you haven’t create. Don’t worry, if it shows in red color

STEP 5 – Create RecyclerViewAdapter Class

We are going to create RecyclerViewAdapter class which extends RecyclerView.Adapter.

Right-click on Java->New->Kotlin File/Class-> Put the class name as RecyclerViewAdapter and make it the same as the below code.

class RecyclerViewAdapter(var months_array: Array)
{

}

STEP 6 – Create A Custom ViewHolder Class And Extend Adapter Class With RecyclerView.Adapter

In this step, You will create an inner ViewHolder class by extending RecyclerView.ViewHolder. After initializing views in ViewHolder, makes RecyclerViewAdapter extends RecyclerView.Adapter with ViewHolder as the generic parameter. Just like below

class RecyclerViewAdapter(var months_array: Array) : RecyclerView.Adapter()
{

    inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)
  {
      var textview = itemView.textview
  }
}

  • Creates Inner class ViewHolder which extends RecyclerView.ViewHolder
  • Inside viewholder class, initialize row_layout elements. here, TextView.
  • If there is red wavy underline below the RecyclerViewAdapter, then click ALT + ENTER. select implement members
  • select onCreateViewHolder(),onBindViewHolder() and getItemCount() and click OK
class RecyclerViewAdapter(var months_array: Array) : RecyclerView.Adapter()
{
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder 
    {  }

    override fun getItemCount(): Int 
    {   }

    override fun onBindViewHolder(holder: ViewHolder, p1: Int) 
     { }

    inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)
  {
      var textview = itemView.textview
  }
}


STEP 7 – Specify Total Items Using getItemCount() Method

In this step, we will return the array size in getItemCount() method.

    override fun getItemCount(): Int 
    { 
     return months_array.size
    }

  • months_array.length returns 12, JAN to DEC.

    STEP 8 – Create ViewHolder Using onCreateViewHolder() method

    In this step, I will do two important things.
    1. Layout Inflation
    2. Pass it to ViewHolder.

    This is called whenever RecyclerView needs a ViewHolder.

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
        {
            val inflater = LayoutInflater.from(parent.context)
            val view = inflater.inflate(R.layout.row_layout,parent,false)
            return ViewHolder(view)
        }
    
    

    • parent: RecyclerView, viewType: 0, You can have different types of view. Here is only one viewtype, contain value zero.
    • Creates inflater object using context
    • row_layout inflated and become view object
    • Return ViewHolder with view for reference storage purpose

    STEP 9 – Bind ViewHolder With Data In onBindViewHolder()

    Here we will bind our TextView with array item. Access TextView using viewholder. This method calls when the item wants to show, so here we attach data with the view in ViewHolder.

    
    override fun onBindViewHolder(holder: ViewHolder, position: Int)
        {
            holder.textview.text = months_array[position]
        }
    
    
    

    • You can access each element that initialized in ViewHolder class.
    • Here we access textview and set month from string array

    STEP 10 – Set LayoutManager and Adapter

    In this step, You will set LayoutManager and divider, at last, you will attach an adapter too.
    Let’s back to MainActivity. Put the below code in onCreate() and Run.

    
            //sets layoutmanager
            val layoutManager = LinearLayoutManager(this)
            recyclerview.layoutManager = layoutManager
            //sets divider in the list
            val dividerItemDecoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
            recyclerview.addItemDecoration(dividerItemDecoration)
            //Attaches adapter with RecyclerView.
            recyclerview.adapter = adapter
    
    

      • Unlike ListView, We need to implement LayoutManager for RecyclerView. Here we need a Vertical list. Use
      • Make sure you have attached LayoutManger and adapter is not empty, otherwise that may leads to error message
        “e recyclerview no adapter attached skipping layout”

    So use above code and Run

    RecyclerView is ready now.

    STEP 11 – Attach An OnClickListener with Root Element Inside ViewHolder Class

    In this step, you will learn how to get click events and react based on that. Here you will attach OnClickListener with itemView.

                inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
                {
                 var textview = itemView.textview
    
                   init 
                   {
                   itemView.setOnClickListener {
                     Toast.makeText(itemView.context, months_array[adapterPosition],Toast.LENGTH_SHORT).show()
                          }
                   }
    
                 }
            
    

    • init block is called after the constructor
    • Using lambda, Create OnClickListener
    • When item clicks, a toast will appear with Month.
    • getAdapterPosition() method returns the clicked item position, Using Kotlin synthetic property we can use “adapterPositon”here.

    Run again.
    Finally, you have made a simple RecyclerView. Congrats!

    How above RecyclerView Adapter Works?

    how recyclerview works in android

    Okay. let’s clear it out… How RecyclerView adapter works based on the above example?

    • At first, getItemCount() method gets called and that will return 12.
    • After that, for creating ViewHolder, onCreateViewHolder() gets called. It inflates the XML layout and makes View and passes it to ViewHolder for storing references.
    • After that onBindViewHolder() gets called, here we use ViewHolder to access the TextView and attaches text. The 0th row is created.
    • The above process repeats and creates as many ViewHolders to fill the screen and even more. It depends on the screen size and layout size.
    • After that RecyclerView stops calling onCreateViewHolder but onBindViewHolder still repeats its job.

    RecyclerView With CheckBox Example In Android Studio

    recyclerview with checkbox example in android

    In this example, we will create an app that holds CheckBox and its state. While scrolling too.

    Let’s create a project.

    Open your Android Studio.

    Step 1

    Start a new Android Studio project.

    Application Name: RecyclerView With CheckBox In Android Example
    Company Domain: androidride.com

    Check Include Kotlin Support.


    Step 2

    Select form factors and minimum SDK

    Select API 15: IceCreamSandwich and Click Next.


    Step 3

    Add Empty activity to Project.


    After creating the project

    build.gradle(Module.app)

    Add the below code to the dependencies section.

    
    
    //androidx library users
    
        implementation 'androidx.cardview:cardview:1.0.0'
        implementation 'androidx.recyclerview:recyclerview:1.1.0'
    
    /*
    *If you are using the support library
        *implementation 'com.android.support:recyclerview-v7:28.0.0'
        * implementation 'com.android.support:cardview-v7:28.0.0'
        * 
        * */
    
    
    • For Kotlin users, Make sure that you have using kotlin-android-extensions

    activity_main.xml

    
    
    
    
    
    
    
    • It creates a RecyclerView with Vertical scrollbars and assigns id “recyclerview”.
    • If you are using the support library, replace androidx.recyclerview.widget.RecyclerView with android.support.v7.widget.RecyclerView.

    checkbox_row.xml

    
    
    
    
        
    
    
    
    
    • Creates a CheckBox inside a CardView.
    • Support library users – replace androidx.cardview.widget.CardView with android.support.v7.widget.CardView.

    Data.kt

    
    package com.androidride.recyclerviewwithcheckboxinandroidexample
    
    data class Data(var position: Int)
    
    
    • Only one property : position – We can pass it through constructor

    MainActivity.kt

    
    
    class MainActivity : AppCompatActivity()
    {
    
        var list = ArrayList()
    
        lateinit var  adapter : RecyclerViewAdapter
    
        override fun onCreate(savedInstanceState: Bundle?)
        {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            setupdata()
    
            adapter = RecyclerViewAdapter(list)
            //sets layoutmanager
            recyclerview.layoutManager = LinearLayoutManager(this)
            //sets adapter
            recyclerview.adapter = adapter
    
        }
    
        private fun setupdata()
        {
            for(i in 1..30)
            {//creates data object and add it to list.
                var data = Data(i)
    
                list.add(data)
            }
        }
    }
    
    
    

    RecyclerViewAdapter.kt

    
    
    class RecyclerViewAdapter(var list: ArrayList) : RecyclerView.Adapter()
    {
    
        var checkBoxStateArray = SparseBooleanArray()
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
        {
            val context = parent.context
    //creates inflater
            val inflater = LayoutInflater.from(context)
    //inflates checkbox_row
            val view = inflater.inflate(R.layout.checkbox_row,parent,false)
    //returns ViewHolder with view.
            return ViewHolder(view)
        }
    //returns no of elements, 30
        override fun getItemCount(): Int = list.size
    
        override fun onBindViewHolder(holder: ViewHolder, position: Int)
        {
    
            if(!checkBoxStateArray.get(position,false))
            {//checkbox unchecked.
                holder.checkbox.isChecked = false
            }
            else
            {//checkbox checked
                holder.checkbox.isChecked = true
            }
    //gets position from data object
            var data_position = list.get(position).position
    //sets text with checkbox
            holder.checkbox.text = "CheckBox $data_position"
    
        }
    
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
        {//Using Kotlin Android Extensions, access checkbox
            var checkbox = itemView.checkbox
    
            init
            {//called after the constructor.
    
                checkbox.setOnClickListener {
    
                if(!checkBoxStateArray.get(adapterPosition,false))
                {//checkbox checked
                    checkbox.isChecked = true
                 //stores checkbox states and position
                    checkBoxStateArray.put(adapterPosition,true)
                }
                else
                {//checkbox unchecked
                    checkbox.isChecked = false
    //stores checkbox states and position.
                    checkBoxStateArray.put(adapterPosition,false)
                }
    
                }
            }
    
    
        }
    }
    

    • Using Kotlin synthetic properties, we can use adapterPosition for getAdapterPosition()
    • Using SparseBooleanArray, we stores position and boolean value

    Now run the project.

    recyclerview with checkbox in android example - output

    oh, that’s a long tutorial.

    Finally, We are here.

    Guys, Shares really encourage me to create more rich content. Please share this post with your colleagues, family, and friends.