In this final example, you will create an image carousel with indicator.
Do not forget to add dependency in pubspec.yaml,
carousel_slider: ^3.0.0
cupertino_icons: ^1.0.0
open main.dart file, paste the below code.
When a page or image changes, onPageChanged gets called and sets _currentIndex
Using Row’s mainAxisAlignment, property you can change the location of Indicator. Here, I have used mainAxisAlignment: MainAxisAlignment.center – You can change it into MainAxisAlignment.start or any other values.
You can also use Image.asset() – if you are loading image from the assets.
That’s all for now. Please share it with your friends and family. Thank you.
Conclusion
Most of the apps nowadays showing titles at the top and center of the AppBar. So the idea is not new and you can easily set it in Flutter. By default, Flutter comes with what we need, Using first example you can easily understand that. If you want to customize a little bit then you can go for the second one. Third one is SliverAppbar example, which gives an animation look. Depends on your need customize it and use it in your app. Using those three examples, I assume you will learn how to center appbar title in Flutter.
While taking a screenshot, or updating a widget behind the debug banner (For example, the cart icon in the e-commerce app). Developers may get irritated due to the debug banner. So, sometimes it’s better to hide. Using the MaterialApp property is one of the easiest ways to remove it. Just one line of code, that’s done. But you can also test the other ways depending on your needs. If any steps I have missed, you can comment below.
Actually, this example is not necessary. Because we already did it using AssetImage. Here we just changing with NetworkImage. Sometimes, this may help beginners.
When the User tap on ElevatedButton (You can use RaisedButton, FlatButton or FloatingActionButton) after typing username and password, control goes to _printFormValues() method.
If the validation is successful, It will print form values. Otherwise, shows validation errors.
Validation Demo:
Using Form and TextFormFields, It’s easier to make a login page and also helpful to validate the inputs.
autofocus:true enables focus on username TextFormField.
When username is typed and taps on the softkeyboard bottom Right Corner key defined using textInputAction: TextInputAction.next. It calls onFieldSubmitted(), and Change focus to next TextFormField.
Path provider methods – getApplicationDocumentDirectory() to latest ones
You can use these 8 methods to access device storage.
getApplicationDocumentsDirectory(): Gives path to the directory where Application can place it’s private files, Files only get wiped out when application itself removed. iOS – NSDocumentsDirectory API. Android – returns AppData directory.
final directory = await getApplicationDocumentsDirectory();
getTemporaryDirectory(): This gives path to the temporary directory in device. Files can be deleted at any time. iOS – It uses NSCachesDirectory API Android – Use getCacheDir API
getExternalStorageDirectories: It returns list of path of directories where app’s specific data can be stored. Commonly, path lives in external storage partitions or SD cards. Now it’s only available in Android, So before use, it’s better to find out the operating system. on iOS, it shows UnSupportedError. Android: it returns Context.getExternalFilesDirs(String type). Below API 19: Context.getExternalFilesDir(String type).
getExternalStorageDirectory(): Only available in Android. Provides path to External storage(Generally SD card).
This does not support in iOS, it will throw UnSupportedError if you use it.
getDownloadsDirectory(): It returns path of the directory where downloaded files get stored. Not available in Android and iOS, it gives UnSupportedError.
getExternalCacheDirectories(): It returns list of path of directories where app’s external cache data get stored. Commonly, these types of paths lives in SD cards and only available in Android, better check it out which OS is running because iOS throws UnSupportedError.
Android – returns Context.getExternalCacheDirs(). Below API 19 : Context.getExternalCacheDir() API.
getLibraryDirectory():It returns path of the directory where app store persistent data such as sqlite.db, Not available in Android.
getApplicationSupportDirectory(): It returns the directory where app place support files. It’s not recommended to use for user data files.
Before creating UI, let’s create createDir() method which creates directory.
createDir() async {
final directoryName = 'AndroidRide';
final docDir = await getApplicationDocumentsDirectory();
final myDir = Directory('${docDir.path}/$directoryName');
if (await myDir.exists()) {
print(myDir.path);
}
final dir = await myDir.create(recursive: true);
print(dir.path);
}
This is the latest version. Starting from 0.6.7, API has changed a lot, If you are using the old versions of this plugin, You should migrate to the new version.
Most important, pickImage is deprecated, you should use ImagePicker.getImage() method instead.
iOS developers – You need to add some key value pairs in this file /ios/Runner/Info.plist
NSPhotoLibraryUsageDescriptionNeed to take picture from photo library
This will show iOS users when they tried to open the photo library.
NSCameraUsageDescriptionNeed to take picture using Camera
You don’t need to do anything with Android if you are trying to develop Apps for API 29+
If you are targeting API level below 29, then you need to add
android:requestLegacyExternalStorage="true"
Clean main.dart file and put the below code. You can easily create StatefulWidget by typing stful.
First, you need to create instance of ImagePicker and File.
then you need to import below statements.
import ‘dart:io’;
import ‘package:image_picker/image_picker.dart’;
Let’s create image taking method called _getImage().
//ImageSource: Camera and Gallery.
_getImage(ImageSource imageSource) async
{
PickedFile imageFile = await picker.getImage(source: imageSource);
//if user doesn't take any image, just return.
if (imageFile == null) return;
setState(
() {
//Rebuild UI with the selected image.
_image = File(imageFile.path);
},
);
}
You can directly use ImageSource.camera or ImageSource.gallery in getImage() method. In this way you can implement both features and reduce code.
Let’s talk about ImagePicker pickImage() arguments:
source: Gallery or Camera.
imageQuality: value ranges from 0-100, where 100 is max/original quality. If it’s null, the original quality returned.
maxHeight: specify the maximum height of the Image, if it’s not specified original height returned.
maxWidth: specify the maximum width of the Image, if it’s null original width returned.
preferredCameraDevice: By default, it uses CameraDevice.rear. You can change it to CameraDevice.front.
Flutter Image_Picker – Capture Image & Store Example
In this example, you will capture an image using camera and store it in the device storage. Create a Flutter project named imagepicker_save_example open pubspec.yaml, Just like mentioned above, add imagepicker dependency with path and path_provider.
just like the first example, create File and ImagePicker instance in state class.
File _image;
final picker = ImagePicker();
Now it’s time to make _getImage() and store it in the device storage.
_getImage() async
{
//ImageSource: camera
PickedFile imageFile = await picker.getImage(source: ImageSource.camera);
//If there is no image selected, return.
if (imageFile == null) return;
//File created.
File tmpFile = File(imageFile.path);
//it gives path to a directory - path_provider package.
final appDir = await getApplicationDocumentsDirectory();
//filename - returns last part after the separator - path package.
final fileName = basename(imageFile.path);
//copy the file to the specified directory and return File instance.
tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
//prints file location
print('File path is :${tmpFile.path}');
setState(() {
_image = tmpFile;
});
}
How to view those Image Files stored in Emulator/Device?
In Android Studio, View -> Tool Windows -> Device File Explorer. Based on this example, images located inside data/data/com.example.imagepicker_save_example/app_flutter/image files.
How to take Video from Gallery or capture using Camera – Flutter ImagePicker
Using ImagePicker, you can pick and capture videos too. So in this example, you will select or record video using ImagePicker and play it using video_player.
So create a project named flutter_imagepicker_video_example, that’s a long name.
After the project created, open pubspec.yaml and paste the below dependencies,
video_player: ^1.0.1
image_picker: ^0.6.7+14
iOS – ImagePicker
put below keys to info.plist file, located in /ios/Runner/Info.plist.
if you are making an app for the above API 29, there is no configuration required. For below API 29, add the below attribute to the tag in AndroidManifest.xml.
android:requestLegacyExternalStorage="true"
Let’s configure video_player…
iOS – video_player
Paste below entries to info.plist file
NSAppTransportSecurityNSAllowsArbitraryLoads
Actually, these keys allow using Video files by URLs.
Android
paste the permission in AndroidManifest.xml
clear your main.dart file and make statefulWidget by typing stful and paste below code.
In this post, you will learn about the Flutter Swiper package. Using this library, you can create image Carousel.
Let’s make a simple image carousel like above.
Create a Flutter project in Android Studio or Visual Studio. If you don’t know how to create a Flutter project in Android Studio, then read this post Android Studio Flutter Project Setup.
When user taps on image, it prints image url from the imageList
If you are trying to refresh the UI after onTap triggered, then you must convert the class into a StatefulWidget and call setState() inside onTap method block.
Stack Layout Example
In this example, you will learn how to make a stack layout carousel using the same Image URLs used in the first example.
What is FloatingActionButton or Floating Button in Flutter?
FloatingActionButton is a simple button floating above the body at the bottom right corner. Provides immediate access for a primary function.
For example, the Gmail app.
When you are trying to composing a new mail, you are tapping the FloatingActionButton.
How to make a FloatingActionButton in Flutter
It’s very simple because Scaffold provides a floatingActionbutton property. You just need to give its value. Okay…Let’s create a simple Flutter project with FloatingActionbutton.
This is just a simple example, If you want to redraw your widget you need to convert StatelessWidget in to StatefulWidget and call setState() method.
There are 2 types of FloatingActionButton constructors are available now.
1) FloatingActionButton() constructor – You have seen that how to use this constructor in above example. 2) FloatingActionButton.extended() – It just needs label as extra property.
In this example, you will create a BottomAppBar using bottomNavigationBar property with FloatingActionButton. For aligning FAB, Use Scaffold’s floatingActionButtonLocation property.
When the FAB is clicked, it will call setState method with updating counter variable value.
setState() method re-runs build() method, that updates Text value.
Let’s learn about other FloatingActionButton properties.
How to disable FloatingActionButton in Flutter
It is easy to disable FloatingActionButton, just provide a null value for onPressed property. But it is not recommended, because there is no sign that FAB is disabled, So it’s better to change the background color of FAB while it’s in a disabled state.
How to reduce FloatingActionButton size in Flutter?
By default, FloatingActionButton’s width and height are 56.0 logical pixels. Using mini property, you can reduce the Floating Button size to 48.0 logical pixels in both width and height.
If you want more information about Flutter in less time. You can go for it. . . . . Download Source Code – Subscribe to our Newsletter – Link will send it to you
A quick demo
Okay… Let’s make a simple Flutter project named “flutter_notes“.
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: Helps to expose value. 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. 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.
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.
delete_popup.dart – Just like the name, it shows alertdialog when the delete note button clicks.
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.
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
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
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’;
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.
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:
_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.
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.
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
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.
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
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.
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.