Thursday, June 13, 2024
Google search engine
HomeFirebaseA-Z Header Builder In Flutter

A-Z Header Builder In Flutter

Let’s build an A-Z header List of the firebase snapshot In Your Flutter Apps

In this blog, we shall learn how to implement A-Z header logic on a firebase snapshot containing a list of documents. This functionality is very helpful to the users as it makes it convenient for the users to find the data in a long list using the header title. We will be building the logic to display the header text on the top of the list data containing elements of that specific header. (eg. If the header is “A” then it will show the only element that starts with “A” and like a vise)


Table of contents:

What is flutter?

Connect your app with firebase

Create a collection of users on firebase that contains the data of the users

Install the following dependencies

Initialize the Firebase in your main method

List of users inside the builder method

Fetch the list of users from the database to your app

Initialize the variable outside the build method

UserCard widget

App Screenshot


What is Flutter?

Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time.

Flutter – Beautiful native apps in record time
Paint your app to life in milliseconds with Stateful Hot Reload. Use a rich set of fully customizable widgets to build…flutter. dev

Connect your app with firebase.

How to integrate firebase with flutter android or ios app ?

  1. Open firebase, click on get started which will take you to the Add Project screen.
  2. Enter the project name and complete the other essential steps. It will take you to your project screen, click on the android icon.
  3. Now the steps which are coming are very important so please do them very carefully. You have to enter the package name which is generally your application Id in your app-level build. Gradle file. Add the other two optional fields if you wish to add them as well.
  4. Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory. (NOTE: Please check the file that you have downloaded has a google-services.json name or not because if you download it more than one time the name of the file changes to google-services(2).json, so please remove (2) from the file name or rename it to google-services.json)
  5. You will see the following screen.

Here the first block contains the classpath that you have to add to your project-level build. Gradle file under the dependencies section. The second section contains a plugin and dependencies that you have to add to your project app-level build. Gradle file. Please add these lines properly and carefully if you are adding them for the first time.

Left: project/build.gradle ….Right :project/app/build.gradle

6. Now you should restart your application (NOTE: Please refer to full restart not hot reload). Wait for few seconds and your application will be successfully added with firebase. If you see the bellow screen on your firebase then you have successfully added firebase to your app…

Create a collection of users on firebase that contains the data of the users.

Install the following dependencies.

cloud_firestore: ^0.14.0+2
firebase_core: ^0.5.0

Initialize the Firebase in your main method.

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

Fetch the list of users from the database to your app.

StreamBuilder is a stateful widget that can listen to streams and return widgets and capture snapshots of received stream data from the database.

We will fetch the collection users and we will order it according to the username field.

StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.orderBy("username")
.snapshots(),
builder: (context, userSnapshot) {
return ;
},
)

List of users inside the builder method.

StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.orderBy("username")
.snapshots(),
builder: (context, userSnapshot) {
return userSnapshot.hasData
? ListView.builder(
itemCount: userSnapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot userData =
userSnapshot.data.documents[index];

return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
})
: CircularProgressIndicator();
},
),

Initialize the variable outside the build method

String header;
String username;
String _username;
String currentHeader;

Logic: To implement the following functionality we need to get the username of the current index and the username of the previous index i.e. index-1 and we will store it into _username. We will assign both the username substring to two different variables currentheader and header respectively. Now we will compare both the header if they are equal then the Usercard widget will be displayed if not then the Column of the Header text and Usercard widget will be displayed.

ListView.builder(
itemCount: userSnapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot _userData = index == 0
? userSnapshot.data.documents[index]
: userSnapshot.data.documents[index - 1];

DocumentSnapshot userData =
userSnapshot.data.documents[index];

username = userData.data()['username'];
_username = index == 0
? userData.data()['username']
: _userData.data()['username'];
currentHeader = username.substring(0, 1);
header = index == 0
? username.substring(0, 1)
: _username.substring(0, 1);
 if (index == 0 || index == 0
? true
: (header != currentHeader)) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.only(
left: 30, top: 10, bottom: 10),
child: Text(
currentHeader,
style: TextStyle(
fontWeight: FontWeight.bold),
)),
UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl:
userData.data()['image_url'])
],
);
} else {
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
}
})

UserCard widget

import 'package:flutter/material.dart';
import 'package:laundary_wender_application/userOrderPage.dart';

class UserCard extends StatelessWidget {
final String userImageUrl;
final String userLaundryBagNo;
final String userName;
final String userEmail;
final String userId;

UserCard({
@required this.userEmail,
@required this.userName,
@required this.userId,
@required this.userLaundryBagNo,
@required this.userImageUrl,
});

@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return UserOrderPage(
userId: userId,
);
}));
},
child: Card(
child: Container(
height: 100,
width: MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
CircleAvatar(
backgroundImage: NetworkImage(userImageUrl),
radius: 30,
),
Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
userLaundryBagNo,
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 20,
),
),
Text(
userName,
style: TextStyle(
fontWeight: FontWeight.w700, color: Colors.grey),
),
Text(
userEmail,
style: TextStyle(
fontWeight: FontWeight.w500, color: Colors.grey),
)
],
),
),
],
),
),
),
),
);
}
}

Demo Screenshot

🌸🌼🌸 Thank you for reading. 🌸🌼🌸


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app 987tr project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments