The getter 'imgUrl' was called on null - firebase

I want to get the value of (profile.imgUrl) from Firestore but I get error:
The getter 'imgUrl' was called on null.
Receiver: null
Tried calling: imgUrl
Although the user is signed in and I can get the data in the home page but when I navigate to Account page it gives me this error.
class Account extends StatelessWidget {
final Profile profile;
Account({this.profile});
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
print(profile.imgUrl);
return StreamProvider<List<Profile>>.value(
value: DatabaseService().profiles,
child: Scaffold(
body: Stack(
children: <Widget>[
ClipPath(
child: Container(
color: Colors.green.withOpacity(0.8),
),
clipper: getClipper(),
),
Positioned(
width: 400,
top: MediaQuery.of(context).size.height / 5,
child: Column(
children: <Widget>[
Container(
width: 150.0,
height: 150.0,
decoration: BoxDecoration(
color: Colors.green,
image: DecorationImage(
image: NetworkImage(profile.imgUrl),
fit: BoxFit.cover),
borderRadius: BorderRadius.all(Radius.circular(75.0)),
boxShadow: [
BoxShadow(blurRadius: 7.0, color: Colors.black)
]),
),
SizedBox(
height: 90.0,
),
Text(
'Alex Ali',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30.0,
fontFamily: 'Montserrat',
letterSpacing: 1.5),
),
SizedBox(
height: 15.0,
),
Text(
'New Seller',
style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 17.0,
color: Colors.green),
),
SizedBox(
height: 25,
),
Container(
height: 30.0,
width: 95.0,
child: Material(
borderRadius: BorderRadius.circular(20.0),
shadowColor: Colors.greenAccent,
color: Colors.green,
elevation: 7.0,
child: GestureDetector(
onTap: () {
print(profile.imgUrl);
},
child: Center(
child: Text(
'Edit Name',
style: TextStyle(color: Colors.white),
),
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: 30.0,
width: 95.0,
child: Material(
borderRadius: BorderRadius.circular(20.0),
shadowColor: Colors.redAccent,
color: Colors.red,
elevation: 7.0,
child: GestureDetector(
onTap: () async {
await _auth.signOut();
},
child: Center(
child: Text(
'Log out',
style: TextStyle(color: Colors.white),
),
),
),
),
)
],
),
)
],
)
),
);
}
}
class getClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
var path = new Path();
path.lineTo(0.0, size.height / 1.9);
path.lineTo(size.width + 125, 0.0);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return true;
}
}
and that is Home page code:
class Home extends StatefulWidget {
#override
_Home createState() => _Home();
}
class _Home extends State<Home> {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
return StreamProvider<List<Profile>>.value(
value: DatabaseService().profiles,
child: Scaffold(
body: SafeArea(
child: ListView(
padding: EdgeInsets.symmetric(vertical: 30.0),
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 20.0, right: 120.0),
child: Text(
"What would you like to find?",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
),
SizedBox(height: 20.0),
SizedBox(
height: 20.0,
),
SizedBox(height: 500, child: ProfileList()),
],
),
),
),
);
}
}
Here is the code that opens Account page through BottomNavigationBar:
class Wrapper extends StatefulWidget {
#override
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
int _currentTab = 0;
final _page = [
Home(),
Search(),
Account(),
];
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
print(user);
if (user == null) {
return Authenticate();
} else {
return Scaffold(
body: _page[_currentTab],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentTab,
onTap: (int value) {
setState(() {
_currentTab = value;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
size: 30.0,
),
title: SizedBox.shrink()),
BottomNavigationBarItem(
icon: Icon(
Icons.search,
size: 30.0,
),
title: SizedBox.shrink()),
BottomNavigationBarItem(
icon: Icon(
Icons.person,
size: 30.0,
),
title: SizedBox.shrink(),
)
]),
);
}
}
}

You need to pass a Profile as a parameter when Account is created.
That should be done dynamically, so you can't use a fixed list.
Instead of doing this:
final _page = [
Home(),
Search(),
Account(),
];
Scaffold(
body: _page[_currentTab],
// ...
)
You should do something like this:
Widget _getPage(int pos, user User) {
switch (pos) {
case 0:
return Home();
case 1:
return Search();
case 2:
return Account(user.profile); // Assuming profile is a member of user
default:
return Container();
}
}
Scaffold(
body: _getPage(_currentTab, user),
// ...
)

Related

Null check operator used on a null value while querying the User-Data

So I am creating a chat-app. I need to show the list of all users in the firebase by mentioning their user-name and email.
I am getting the above stated error on line 56.
Also if I remove the null check operator in the line
QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
And replace late at the beginning it will produce late initialization error.
import 'package:chatapp/services/database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class Search extends StatefulWidget {
_Search createState() => _Search();
}
class _Search extends State<Search> {
QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
bool isLoading = false;
bool haveUserSearched = false;
DatabaseMethods databaseMethods = new DatabaseMethods();
var searchEditingController = TextEditingController();
InitiateSearch() async {
if (searchEditingController.text.isNotEmpty) {
setState(() {
isLoading = true;
});
await databaseMethods.GetUserByUsername(searchEditingController.text)
.then((snapshot) {
searchResultSnapshot = snapshot;
print("$searchResultSnapshot");
setState(() {
isLoading = false;
haveUserSearched = true;
});
});
}
}
Widget UserList() {
return Container(
height: 500,
child: ListView.builder(
itemCount: searchResultSnapshot?.docs.length,
itemBuilder: (context, index) {
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"],
searchResultSnapshot?.docs[index].data()["userEmail"],
);
}),
);
}
Widget UserTile(String? userName, String? userEmail) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
userName!, //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail!,
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
),
Spacer(),
GestureDetector(
onTap: () {
null;
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(24)),
child: Text(
"Message",
style: TextStyle(color: Colors.white, fontSize: 16),
),
),
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onPressed: () {
Navigator.pop(context);
});
},
),
title: Text('Search'),
),
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: [
Container(
height: 36,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Colors.black,
),
BoxShadow(
color: Colors.black,
spreadRadius: -12.0,
blurRadius: 12.0,
),
],
),
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 0, horizontal: 10.0),
child: TextFormField(
style: TextStyle(color: Colors.black),
controller: searchEditingController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Search',
hintStyle: TextStyle(color: Colors.grey),
icon: GestureDetector(
onTap: () {
InitiateSearch();
},
child: Icon(
Icons.search,
color: Colors.grey,
),
),
suffixIcon: IconButton(
onPressed: searchEditingController.clear,
icon: Icon(
Icons.cancel_rounded,
color: Colors.grey,
),
),
),
),
),
), //Search
SizedBox(
height: 12,
),
UserList(),
],
),
));
}
}
Here is my Database file.
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseMethods {
GetUserByUsername(String username) async {
return await
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["userName"]);
});
});
}
Future<void> UploadUserInfo(userData) async {
FirebaseFirestore.instance.collection("users").add(userData).catchError((e) {
print(e.toString());
});
}
}
I would really appritiate your help on this.
You can replace below piece of code
children: [
Text(
userName!, //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail!,
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
with
children: [
Text(
userName ?? "", //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail ?? "",
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
In place of
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"],
searchResultSnapshot?.docs[index].data()["userEmail"],
);
use this
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"]??"",
searchResultSnapshot?.docs[index].data()["userEmail"]??"",
);
And replace the String? with String in (Remove ?)
Widget UserTile(String userName, String userEmail)
and use the value like the following
Text(userName,style: TextStyle(color: Colors.white, fontSize: 16),),

How to compare two values from two different collections from firebase?

Below is the vehicle uploading details file code that uploads details on the firebase. It uploads city, vehicle type, and phone number. I wanted to search for vehicle in the specified city. So basically it matches the details of user. For example a person wants to book vehicle in city Lahore and vehicle type Car so this should search in database if anyone uploaded details matching the description and show it to the user.
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flash_chat/constants.dart';
import 'package:flash_chat/constraints/rounded_button.dart';
import 'package:flash_chat/screens/Home.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:image_picker/image_picker.dart';
class UploadingVehicle extends StatefulWidget {
static const id = 'uploading_vehicle';
#override
_UploadingVehicleState createState() => _UploadingVehicleState();
}
class _UploadingVehicleState extends State<UploadingVehicle> {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
bool showSpinner = false;
static String uCity;
String description;
String phoneNumber;
String uDropdownvalue = 'Hiace';
var vehicles = ['Car','Suzuki Bolan','Hiace'];
File _image1,_image2,_image3;
String id;
final Picker = ImagePicker();
_UploadingVehicleState();
_imgFromCamera() async {
final image = await Picker.pickImage(
source: ImageSource.camera, imageQuality: 50
);
setState(() {
_image1 = File(image.path);
});
}
_imgFromGallery(String id) async {
final image = await Picker.pickImage(
source: ImageSource.gallery, imageQuality: 50
);
if(id == 'A'){
setState(() {
_image1 = File(image.path);
});
}else if(id == 'B'){
setState(() {
_image2 = File(image.path);
});
}
else if(id == 'C'){
setState(() {
_image3 = File(image.path);
});
}
}
void _showPicker(context, String id) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Photo Library'),
onTap: () {
_imgFromGallery(id);
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.black, //change your color here
),
title: Text('Upload vehicle'.toUpperCase(),
style: TextStyle(color: Colors.black)),
backgroundColor: Colors.yellowAccent.shade700,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back)),
actions: [
Icon(Icons.person),
],
),
body: SafeArea(
child: Container(
child: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 40,
),
Material(
elevation: 18,
shadowColor: Colors.black,
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kRegisterTextFieldDecoration.copyWith(
prefixIcon: Icon(Icons.location_city,
color: Colors.black,
),
hintText: 'Enter City',
fillColor: Colors.white,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
autofocus: true,
onChanged: (value){
uCity = value;
},
),
),
SizedBox(
height: 40,
),
Material(
elevation: 18,
shadowColor: Colors.black,
child: TextField(
style: TextStyle(
color: Colors.black,
),
keyboardType: TextInputType.number,
decoration: kRegisterTextFieldDecoration.copyWith(
prefixIcon: Icon(
Icons.phone,
color: Colors.black,
),
hintText: 'Enter Phone Number',
fillColor: Colors.white,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
focusColor: Colors.blue,
),
onChanged: (value){
phoneNumber = value;
},
),
),
SizedBox(
height: 40,
),
Row(
children: <Widget>[
Text(
'Select Vehicle:',
style: TextStyle(
color: Colors.blue,
fontSize: 15,
),),
SizedBox(
width: 20,
),
Center(
child: DropdownButton<String>(
value: uDropdownvalue,
elevation: 16,
dropdownColor: Colors.white,
icon: Icon(Icons.arrow_downward,
color: Colors.black,
),
style: TextStyle(
color: Colors.black,
fontSize: 15,
),
underline: Container(
height: 1,
color: Colors.black,
),
items: vehicles.map<DropdownMenuItem<String>>((String vehicle) {
return DropdownMenuItem<String>(
value: vehicle,
child: Text(vehicle),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
uDropdownvalue = newValue;
});
},
),
),
],
),
SizedBox(
height: 20,
),
Text(
'Add Description:',
style: TextStyle(
color: Colors.blue,
fontSize: 18,
),
),
Expanded(
child: Container(
child: TextField(
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
)
),
),
style: TextStyle(
color: Colors.black,
),
onChanged: (value){
description=value;
},
),
),
),
Row(
children: [
Expanded(
child: buildGestureDetector(context,_image1),
),
Expanded(
child: buildGestureDetector(context,_image2),
),
Expanded(
child: buildGestureDetector(context,_image3),
),
],
),
Roundedbutton(
color: Colors.yellow,
title: 'Upload vehicle',
onPressed: () async {
setState(() {
showSpinner = true;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Details uploaded successfully')),
);
_firestore.collection('Uploading Vehicle Details').add({
'City': uCity,
'Vehicle': uDropdownvalue,
'Description' : description,
'Phone.No#' : phoneNumber,
});
Navigator.pushNamed(context, HomeScreen.id);
},
),
],
),
),
),
),
),
);
}
GestureDetector buildGestureDetector(BuildContext context, File _image) {
//GestureDetector({#required this._image});
//File _image;
return GestureDetector(
onTap: () {
_showPicker(context, 'A');
},
child: CircleAvatar(
radius: 53,
backgroundColor: Colors.black,
child: _image != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.file(
_image,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
),
)
: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(50)),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
color: Colors.grey[800],
),
),
),
);
}
}
And below is the code for the user who wants to book vehicle in his city. So it should search in firebase if the required details are present in the firebase or not. If yes it should retrieve the details from the firebase and show it to the person who's looking for it.
import 'package:flash_chat/constants.dart';
import 'package:flash_chat/constraints/rounded_button.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:flash_chat/screens/uploading_vehicle.dart';
class Booking extends StatefulWidget {
static const id = 'booking';
#override
_BookingState createState() => _BookingState();
}
class _BookingState extends State<Booking> {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
final UploadingVehicle uv = new UploadingVehicle();
bool showSpinner = false;
String city;
String dropdownvalue = 'Hiace';
var vehicles = ['Car','Suzuki Bolan','Hiace'];
Object get uCity => null;
Object get uDropdownvalue => null;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.black, //change your color here
),
title: Text('Book vehicle'.toUpperCase(),
style: TextStyle(color: Colors.black)),
backgroundColor: Colors.yellowAccent.shade700,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back)),
actions: [
Icon(Icons.person),
],
),
body: SafeArea(
child: Container(
child: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 40,
),
Material(
elevation: 18,
shadowColor: Colors.black,
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kRegisterTextFieldDecoration.copyWith(
hintText: 'Enter City',
fillColor: Colors.white,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
onChanged: (value){
city=value;
},
),
),
SizedBox(
height: 40,
),
Row(
children: <Widget>[
Text(
'Select Vehicle:',
style: TextStyle(
color: Colors.blue,
fontSize: 15,
),),
SizedBox(
width: 20,
),
Center(
child: DropdownButton<String>(
value: dropdownvalue,
elevation: 16,
dropdownColor: Colors.white,
icon: Icon(Icons.arrow_downward,
color: Colors.black,
),
style: TextStyle(
color: Colors.black,
fontSize: 15,
),
underline: Container(
height: 1,
color: Colors.black,
),
items: vehicles.map<DropdownMenuItem<String>>((String vehicle) {
return DropdownMenuItem<String>(
value: vehicle,
child: Text(vehicle),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
dropdownvalue = newValue;
});
},
),
),
],
),
Roundedbutton(
color: Colors.yellow,
title: 'Search for vehicle',
onPressed: () async {
setState(() {
showSpinner = true;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Searched')),
);
_firestore.collection('Booking Details').add({
'City': city,
'Vehicle': dropdownvalue,
});
Navigator.pushNamed(context, Booking.id);
},
),
Container(
color: Colors.white,
child: Text('Details matched',
style: TextStyle(
color: Colors.black,
fontSize: 30,
),
)
: Text(
'Details not matched',
style: TextStyle(
color: Colors.black,
fontSize: 30,
),),
),
],
),
),
),
),
),
);
}
}
How am I supposed to do this?
As far as I can tell from the massive amount of code you shared, this is the code that adds the vehicle details to the database:
_firestore.collection('Uploading Vehicle Details').add({
'City': uCity,
'Vehicle': uDropdownvalue,
'Description' : description,
'Phone.No#' : phoneNumber,
});
If you want to search that information, you can use a query such as this one:
_firestore.collection('Uploading Vehicle Details')
.where('City', isEqualTo: 'San Francisco')
.where('Vehicle', isEqualTo: 'Toyota RAV4')
.get()
.then(...);
If you want to show this in the UI, you'll want to use snapshots instead of get and wrap it in a StreamBuilder as shown in the documentation on listening to realtime changes.

How to update the Circular Percentage Indicator once we click each Checkbox List

I want to do the checklist section which have circular percentage indicator. The percentage should updated once the list of checklist(checkbox) is clicked. Each Checkbox should hold 25% because have 4 checklist and the overall percentage is 100. Please help me how to update the percentage.
This is the interface
class ReportForm extends StatefulWidget {
final int itemIndex;
final Project project;
const ReportForm({this.itemIndex, this.project});
#override
State<ReportForm> createState() => _ReportFormState();
}
class _ReportFormState extends State<ReportForm> {
FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
UserModel loggedInUser = UserModel();
double progress = 0.0;
currentProgressColor() {
if (progress >= 0.6 && progress < 0.8) {
return Colors.red;
}
if(progress >= 0.8){
return Colors.green;
}
else{
return Colors.orange;
}
}
final checklist = [
CheckBoxState(title: 'Attendance'),
CheckBoxState(title: 'Equipment Used'),
CheckBoxState(title: 'Work Performed'),
CheckBoxState(title: 'Remarks'),
];
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Container(
height: 650,
width: 370,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(13),
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
blurRadius: 17,
spreadRadius: -23,
color: kShadowColor,
),
],
),
child: Column(
children: <Widget>[
SizedBox(
height:40,
),
CircularPercentIndicator(
radius: 200.0,
circularStrokeCap: CircularStrokeCap.round,
lineWidth: 25.0,
progressColor: currentProgressColor(),
percent: progress,
animation: true,
animationDuration: 1500,
center: new Text("${this.progress * 100}%", style: TextStyle(
fontSize: 30,
),),
footer: new Text("Daily Report Completion",
style: TextStyle(
fontSize: 15,
color: Colors.green,
),),),
SizedBox(
height:20,
),
StreamBuilder<QuerySnapshot>(
stream: _firebaseFirestore.collection("Attendance").snapshots(),
builder: (context, snapshot) {
return GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => Attendance(
),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height:60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Attendance')),
),
),
),
);
}
),
SizedBox(
height:18,
),
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => DetailsForm(project: widget.project, itemIndex: widget.itemIndex),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height: 60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Equipment Used')),
),
),
),
),
SizedBox(
height:18,
),
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => HomeScreen(),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height: 60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Work Performed')),
),
),
),
),
SizedBox(
height:18,
),
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => Remarks(),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height: 60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Remarks')),
),
),
),
),
],
),
),
);
}
Widget buildSingleCheckbox(CheckBoxState checkbox) => StatefulBuilder(
builder: (context, _setState) => CheckboxListTile(
activeColor: Colors.green,
value: checkbox.value,
title: Text(checkbox.title),
onChanged: (value) =>
_setState(() => checkbox.value = value),
),
);
}
class CheckBoxState{
final String title;
bool value;
CheckBoxState({
#required this.title,
this.value = false,});
}
I did a small test you can apply according to your need
import 'package:flutter/material.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Teste',
debugShowCheckedModeBanner: false,
home: Teste(),
);
}
}
class Teste extends StatefulWidget {
const Teste({Key? key}) : super(key: key);
#override
_TesteState createState() => _TesteState();
}
class _TesteState extends State<Teste> {
List<bool> checkboxStatus = [];
double percentage = 0.0;
final checklist = ['Attendance', 'Equipment Used', 'Work Performed', 'Remarks'];
#override
void initState() {
super.initState();
checklist.forEach((element) => checkboxStatus.add(false));
}
currentProgressColor() {
if (percentage >= 0.6 && percentage < 0.8) {
return Colors.red;
}
if (percentage >= 0.8) {
return Colors.green;
} else {
return Colors.orange;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Container(
height: 650,
width: 370,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(13),
boxShadow: [BoxShadow(offset: Offset(0, 1), blurRadius: 17, spreadRadius: -23, color: Colors.orange)],
),
child: Column(
children: <Widget>[
SizedBox(height: 40),
CircularPercentIndicator(
animateFromLastPercent: true,
radius: 200.0,
circularStrokeCap: CircularStrokeCap.round,
lineWidth: 25.0,
progressColor: currentProgressColor(),
percent: percentage,
animation: true,
animationDuration: 1500,
center: Text('${percentage * 100} %'),
footer: Text("Daily Report Completion", style: TextStyle(fontSize: 15, color: Colors.green)),
),
SizedBox(height: 20),
Expanded(
child: ListView.builder(
itemCount: checklist.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13.0)),
elevation: 10,
child: ElevatedButton(
onPressed: () {
if (checklist[index] == 'Attendance') {
Navigator.push(context, MaterialPageRoute(builder: (context) => Attendance()));
} else if() {
/// other page
}
},
style: ElevatedButton.styleFrom(primary: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(checklist[index], style: TextStyle(color: Colors.black)),
Checkbox(
value: checkboxStatus[index],
onChanged: (value) {
if (checkboxStatus[index] == false) {
percentage += (1 / checklist.length);
} else {
percentage -= (1 / checklist.length);
}
setState(() => checkboxStatus[index] = !checkboxStatus[index]);
},
checkColor: Colors.white,
)
],
),
),
),
);
},
),
)
],
),
),
),
);
}
}

How to navigate without context in List widget Flutter

I am developing a flutter web app in which I have developed custom navbar but I am struggling to add navigation in the navbar items. I've tried Get to navigate without context but unfortunately it isn't working on the list I've created. I did tried to create function and put navigation as required for it but still no luck.
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:shimmer/shimmer.dart';
import 'package:customweb/about.dart';
double collapsableHeight = 0.0;
Color selected = Color(0xffffffff);
Color notSelected = Color(0xafffffff);
class Nav extends StatefulWidget {
#override
_NavState createState() => _NavState();
}
class _NavState extends State<Nav> {
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return SafeArea(
child: Scaffold(
body: Stack(
children: [
Align(
alignment: Alignment.topCenter,
child: Padding(
padding: EdgeInsets.only(top: 250),
child: Image.asset(
"assets/logo.png",
scale: 2,
)),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.only(bottom: 120),
child: Text(
"Download now available on",
style: TextStyle(fontSize: 30),
))),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.only(right: 200, bottom: 50),
child: Image.asset(
"assets/1200px-Google_Play_Store_badge_EN.png",
scale: 8,
))),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.only(left: 200, bottom: 50),
child: Image.asset(
"assets/1200px-Download_on_the_App_Store_Badge.png",
scale: 8,
))),
AnimatedContainer(
margin: EdgeInsets.only(top: 79.0),
duration: Duration(milliseconds: 375),
curve: Curves.ease,
height: (width < 800.0) ? collapsableHeight : 0.0,
width: double.infinity,
color: Color(0xff121212),
child: SingleChildScrollView(
child: Column(
children: navBarItems,
),
),
),
Container(
color: Colors.amber,
height: 80.0,
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
AnimatedTextKit(
animatedTexts: [
FadeAnimatedText(
'Get It',
textStyle: TextStyle(fontSize: 26, color: Colors.white),
),
FadeAnimatedText(
'All Amazing Stuff',
textStyle: TextStyle(fontSize: 22, color: Colors.white),
),
FadeAnimatedText(
'One Platform',
textStyle: TextStyle(fontSize: 24, color: Colors.white),
),
FadeAnimatedText(
'Endless Services',
textStyle: TextStyle(fontSize: 24, color: Colors.white),
),
FadeAnimatedText(
'Available Soon',
textStyle: TextStyle(fontSize: 24, color: Colors.white),
),
],
onTap: () {
print("");
},
),
LayoutBuilder(builder: (context, constraints) {
if (width < 800.0) {
return NavBarButton(
onPressed: () {
if (collapsableHeight == 0.0) {
setState(() {
collapsableHeight = 240.0;
});
} else if (collapsableHeight == 240.0) {
setState(() {
collapsableHeight = 0.0;
});
}
},
);
} else {
return Row(
children: navBarItems,
);
}
})
],
),
),
],
),
),
);
}
}
List<Widget> navBarItems = [
NavBarItem(
text: 'About',
onPressed: () {
Get.to(AboutPage());
},
),
NavBarItem(
text: 'Services',
onPressed: () {
Get.to(AboutPage());
},
),
NavBarItem(
text: 'FAQ',
onPressed: () {
Get.to(AboutPage());
},
),
];
class NavBarItem extends StatefulWidget {
final String text;
final Function onPressed;
NavBarItem({
required this.text,
required this.onPressed,
});
#override
_NavBarItemState createState() => _NavBarItemState();
}
class _NavBarItemState extends State<NavBarItem> {
Color color = notSelected;
#override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (value) {
setState(() {
color = selected;
});
},
onExit: (value) {
setState(() {
color = notSelected;
});
},
child: Material(
color: Colors.transparent,
child: InkWell(
splashColor: Colors.white60,
onTap: () {},
child: Container(
height: 60.0,
alignment: Alignment.centerLeft,
margin: EdgeInsets.symmetric(horizontal: 24.0),
child: Text(
widget.text,
style: TextStyle(
fontSize: 16.0,
color: color,
),
),
),
),
),
);
}
}
class NavBarButton extends StatefulWidget {
final Function onPressed;
NavBarButton({
required this.onPressed,
});
#override
_NavBarButtonState createState() => _NavBarButtonState();
}
class _NavBarButtonState extends State<NavBarButton> {
Widget build(BuildContext context) {
return Container(
height: 55.0,
width: 60.0,
decoration: BoxDecoration(
border: Border.all(
color: Color(0xcfffffff),
width: 2.0,
),
borderRadius: BorderRadius.circular(15.0),
),
child: Material(
color: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: InkWell(
splashColor: Colors.white60,
onTap: () {
setState(() {
widget.onPressed();
});
},
child: Icon(
Icons.menu,
size: 30.0,
color: Color(0xcfffffff),
),
),
),
);
}
}
Any help will be highly appreciated
Hi Asver Seb you are following wrong method. I've recently done a job on flutter web here use my code of navbar/header to build what you are looking for it will do perfectly fine.
class Header extends StatelessWidget {
const Header({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 20, horizontal: 40),
child: Row(
children: <Widget>[
Image.asset(
'assets/images/logo.png',
width: 50,
),
SizedBox(width: 10),
Shimmer.fromColors(
baseColor: Colors.transparent,
highlightColor: Colors.amber,
child: Text(
"Webster",
style: TextStyle(fontSize: 32, fontWeight: FontWeight.w800),
)),
Spacer(),
NavItem(
title: 'Home',
tapEvent: () {
Get.to(HomeScreen());
},
),
NavItem(
title: 'About',
tapEvent: () {
Get.to(About());
},
),
NavItem(
title: 'FAQ',
tapEvent: () {
Get.to(Faq());
},
),
],
),
);
}
}
class NavItem extends StatelessWidget {
const NavItem({Key? key, required this.title, required this.tapEvent})
: super(key: key);
final String title;
final GestureTapCallback tapEvent;
#override
Widget build(BuildContext context) {
return InkWell(
onTap: tapEvent,
hoverColor: Colors.transparent,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: Text(
title,
style: TextStyle(fontWeight: FontWeight.w300),
),
),
);
}
}

Flutter/Firebase: How to reduce StreamBuilder call on push/pop call?

I have a screen with a bottomNavigationBar:
class AttendantMainPage extends StatefulWidget {
final String? email;
AttendantMainPage({
Key? key,
this.email,
}) : super(key: key);
#override
_AttentdantMainPageState createState() => _AttentdantMainPageState();
}
class _AttentdantMainPageState extends State<AttendantMainPage> {
var user = FirebaseAuth.instance.currentUser;
int _currentIndex = 1;
late final List<Widget> _children;
#override
void initState() {
_children = [
ProfilePage(),
AttendantHomePage(),
ChatListPage(),
];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.white,
selectedItemColor: Color(0xffe96cbd),
onTap: onTabPressed,
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
icon: new Icon(
CustomIcons.user,
),
label: 'Profile'),
BottomNavigationBarItem(
icon: new Icon(
CustomIcons.home,
),
label: 'Home'),
BottomNavigationBarItem(
icon: new Icon(
Icons.mail,
),
label: 'Messages'),
],
),
);
}
void onTabPressed(int index) {
setState(() {
_currentIndex = index;
});
}
}
And i have streamBuilder in all of the screens. When I'm changing screens my stream builders are being called again and again. It may be really expensive using firebase i guess. Here is code of one of the screens, can someone tell me how to avoid unneccessary calls after switching between pages?
class ProfilePage extends StatefulWidget {
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
bool enabled = false;
late FocusNode myFocusNode;
var user = FirebaseAuth.instance.currentUser;
late Stream<DocumentSnapshot> stream;
#override
void initState() {
stream = FirebaseFirestore.instance
.collection('users')
.doc(user!.uid)
.snapshots();
myFocusNode = FocusNode();
super.initState();
}
#override
void dispose() {
// Clean up the focus node when the Form is disposed.
myFocusNode.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
double _width = MyUtility(context).width;
double _height = MyUtility(context).height;
return Scaffold(
backgroundColor: Color(0xfff0eded),
body: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Container(
width: _width,
height: _height,
child: Column(
children: [
Stack(
alignment: AlignmentDirectional.topCenter,
children: [
Container(
width: _width,
height: _height * 0.4,
),
Container(
height: _height * 0.25,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Color(0xff4d629f),
Color(0xffe96cbd),
],
),
),
),
Positioned(
bottom: _height * 0.02,
child: ProfileImage(
width: _width * 0.5,
height: _height * 0.25,
userEmail: user!.email!,
),
),
Positioned(
right: _width * 0.25,
bottom: _height * 0.05,
child: ClipOval(
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(2),
child: ClipOval(
child: Material(
color: Color(0xffe96cbd), // button color
child: InkWell(
splashColor: Color(0xffffc2ea), // inkwell color
child: SizedBox(
width: _width * 0.08,
height: _height * 0.04,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
Icons.edit,
color: Colors.white,
size: MyUtility(context).width * 0.04,
),
)),
onTap: () {
getImage().then((value) {
uploadFile(value);
});
},
),
),
),
),
),
),
),
],
),
Stack(
alignment: AlignmentDirectional.topCenter,
children: [
Padding(
padding: EdgeInsets.symmetric(
vertical: 10,
horizontal: _width * 0.05,
),
child: OverlayPanel(
width: _width * 0.9,
child: Padding(
padding: EdgeInsets.all(
_height * 0.04,
),
child: Column(
children: [
StreamBuilder<DocumentSnapshot>(
stream: stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return TextFormField(
focusNode: myFocusNode,
enabled: enabled,
initialValue: snapshot.data!['username'],
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30,
color: Color(0xff273150),
),
onFieldSubmitted: (input) {
setState(() {
enabled = false;
});
print(input);
FirebaseFirestore.instance
.collection('users')
.doc(user!.uid)
.update({'username': input});
},
);
} else
return TextField(
enabled: false,
style: TextStyle(fontSize: 30),
);
}),
SizedBox(
height: _height * 0.02,
),
Text(user!.email!,
style: TextStyle(
fontSize: 18.0,
color: Color(0xff273150),
)),
Text(
//TODO great idea to use currentUser: user!.displayName as a user Type to check it all easier and faster
'Type: ${'Attendant'}',
style: TextStyle(
fontSize: 14.0,
color: Color(0xff273150),
),
),
],
),
),
),
),
Positioned(
right: _width * 0.1,
top: _height * 0.025,
child: ClipOval(
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(2),
child: ClipOval(
child: Material(
color: Color(0xffe96cbd), // button color
child: InkWell(
splashColor: Color(0xffffc2ea), // inkwell color
child: SizedBox(
width: _width * 0.08,
height: _width * 0.08,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
Icons.edit,
color: Colors.white,
size: _width * 0.04,
),
)),
onTap: () async {
setState(() {
enabled = !enabled;
});
await Future.delayed(
Duration(milliseconds: 10),
() => {
FocusScope.of(context)
.requestFocus(myFocusNode),
});
},
),
),
),
),
),
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: Container(
width: _width,
decoration: BoxDecoration(
color: Color(0xfff0eded),
),
child: Container(
child: Column(
children: [
CustomButton(
width: _width * 0.9,
icon: Icons.lock,
text: 'Change Password',
onPressed: () {
//TODO add possibility to change password
},
),
CustomButton(
width: _width * 0.9,
icon: Icons.delete,
text: 'Delete Account',
onPressed: () {},
),
CustomButton(
width: _width * 0.9,
icon: Icons.logout,
text: 'Log Out',
onPressed: () async {
await FirebaseAuth.instance.signOut();
Navigator.pop(context);
},
),
],
),
),
),
),
],
),
),
),
);
}
}
Changing body in my AttendantMainPage from:
body: _children[_currentIndex],
to
body: IndexedStack(
index: _currentIndex,
children: _children,
),
Solved the problem.
Thanks for help guys!

Resources