How to pass an initial value to the Timer widget - Flutter - firebase

I have this timer from this package https://pub.dev/packages/stop_watch_timer
and I am trying to pass an initial value to it:
DateTime dateNow = DateTime.now () // this is my current Time.
Duration initialTime;
initialTime = dateNow.difference (timeStampfromFirestore.toDate ());
initialTime -> this is the value with which I want the Timer to start, but I have not been able to understand how the package works
for example:
the timer right now starts like this: 00:00:00
I'm trying to make it start like this for example: 00:15:00
where initialTime = 00:15:00
import 'package:flutter/material.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final StopWatchTimer _stopWatchTimer = StopWatchTimer(
onChange: (value) => print('onChange $value'),
onChangeSecond: (value) => print('onChangeSecond $value'),
onChangeMinute: (value) => print('onChangeMinute $value'),
);
final _scrollController = ScrollController();
#override
void initState() {
super.initState();
_stopWatchTimer.rawTime.listen((value) =>
print('rawTime $value ${StopWatchTimer.getDisplayTime(value)}'));
_stopWatchTimer.minuteTime.listen((value) => print('minuteTime $value'));
_stopWatchTimer.secondTime.listen((value) => print('secondTime $value'));
_stopWatchTimer.records.listen((value) => print('records $value'));
_stopWatchTimer.onExecute.add(StopWatchExecute.start);
/// Can be set preset time. This case is "00:01.23".
// _stopWatchTimer.setPresetTime(mSec: 1234);
}
#override
void dispose() async {
super.dispose();
await _stopWatchTimer.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
/// Display stop watch time
Padding(
padding: const EdgeInsets.only(bottom: 0),
child: StreamBuilder<int>(
stream: _stopWatchTimer.rawTime,
initialData: _stopWatchTimer.rawTime.value,
builder: (context, snap) {
final value = snap.data;
final displayTime = StopWatchTimer.getDisplayTime(value);
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Text(
displayTime,
style: TextStyle(
fontSize: 40,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: Text(
value.toString(),
style: TextStyle(
fontSize: 16,
fontFamily: 'Helvetica',
fontWeight: FontWeight.w400),
),
),
],
);
},
),
),
/// Display every minute.
Padding(
padding: const EdgeInsets.only(bottom: 0),
child: StreamBuilder<int>(
stream: _stopWatchTimer.minuteTime,
initialData: _stopWatchTimer.minuteTime.value,
builder: (context, snap) {
final value = snap.data;
print('Listen every minute. $value');
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text(
'minute',
style: TextStyle(
fontSize: 17,
fontFamily: 'Helvetica',
),
),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 4),
child: Text(
value.toString(),
style: TextStyle(
fontSize: 30,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
],
)),
],
);
},
),
),
/// Display every second.
Padding(
padding: const EdgeInsets.only(bottom: 0),
child: StreamBuilder<int>(
stream: _stopWatchTimer.secondTime,
initialData: _stopWatchTimer.secondTime.value,
builder: (context, snap) {
final value = snap.data;
print('Listen every second. $value');
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Text(
'second',
style: TextStyle(
fontSize: 17,
fontFamily: 'Helvetica',
),
),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 4),
child: Text(
value.toString(),
style: TextStyle(
fontSize: 30,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
],
)),
],
);
},
),
),
/// Lap time.
Container(
height: 120,
margin: const EdgeInsets.all(8),
child: StreamBuilder<List<StopWatchRecord>>(
stream: _stopWatchTimer.records,
initialData: _stopWatchTimer.records.value,
builder: (context, snap) {
final value = snap.data;
if (value.isEmpty) {
return Container();
}
Future.delayed(const Duration(milliseconds: 100), () {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut);
});
print('Listen records. $value');
return ListView.builder(
controller: _scrollController,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
final data = value[index];
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Text(
'${index + 1} ${data.displayTime}',
style: TextStyle(
fontSize: 17,
fontFamily: 'Helvetica',
fontWeight: FontWeight.bold),
),
),
const Divider(
height: 1,
)
],
);
},
itemCount: value.length,
);
},
),
),
],
),
),
),
);
}
}

Can be used setPresetTime interface.
Please see.
https://github.com/hukusuke1007/stop_watch_timer
Set Preset Time
Can be set preset time. This case is "00:01.23". When timer is idle state, can be set this.
// Set Millisecond.
_stopWatchTimer.setPresetTime(mSec: 1234);
// Set Hours. (ex. 1 hours)
_stopWatchTimer.setPresetHoursTime(1);
// Set Minute. (ex. 30 minute)
_stopWatchTimer.setPresetMinuteTime(30);
// Set Second. (ex. 120 second)
_stopWatchTimer.setPresetSecondTime(120);

Related

How to change the border colour of a card upon tapping it wrapped in listview.builder in flutter?

I am fetching certain details from firebase and showing them in the form of card, with the help of ListView.Builder. Now, upon tapping a specific card I want to change its border colour to green. I have tried using the flag variable in the setState but it sets the border colour for every card to green. Someone pls have a look at the code I've pasted, and let me know what should be done.This is the image of the UI
Thank You:)
StreamBuilder<QuerySnapshot>(
stream: collectionTests.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
final myDocs = snapshot.data!.docs;
try {
return ListView.builder(
itemCount: myDocs.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.fromLTRB(17, 11, 17, 11),
child: InkWell(
onTap: () {},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: const BorderSide(
color: Colors.white,
),
),
child: ListTile(
contentPadding: const EdgeInsets.all(8),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
myDocs[index]['name'],
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
Card(
color: Colors.indigo,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
myDocs[index]['price'],
style: const TextStyle(
color: Colors.white,
fontStyle: FontStyle.italic,
fontSize: 20,
),
),
),
)
],
),
subtitle: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 12, 8),
child: Text(
myDocs[index]['description'],
style: const TextStyle(
fontSize: 18,
),
),
),
),
),
),
);
},
);
} catch (e) {
return const Center(
child: Card(
child: Text(
'Something went wrong, please check your connection',
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}
}
},
),
Extract your widget into a new stateful class and call the class inside the ListView.
main.dart
import 'package:flutter/material.dart';
import 'package:stackoverflow/custom_card.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, i){
return CustomCard();
},
),
),
);
}
}
custom_card.dart
import 'package:flutter/material.dart';
class CustomCard extends StatefulWidget {
const CustomCard({Key? key}) : super(key: key);
#override
_CustomCardState createState() => _CustomCardState();
}
class _CustomCardState extends State<CustomCard> {
Color borderColor = Colors.black;
#override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
height: 100,
child: GestureDetector(
onTap: (){
setState(() {
borderColor = Colors.green;
});
},
child: Card(
color: borderColor,
),
),
);
}
}
Firstly, you need to define a list that contains bool variables out of build method. These variables will decide whether the border of relevant card is white or green.
List<bool> bordersColors = [];
Then in your listview like this;
return ListView.builder(
itemCount: myDocs.length,
itemBuilder: (context, index) {
bordersColors.add(false);
return Padding(
padding: const EdgeInsets.fromLTRB(17, 11, 17, 11),
child: InkWell(
onTap: () {
setState((){
bordersColors[index] = true;
})
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: const BorderSide(
color: bordersColors[index] ? Colors.green : Colors.white,
),
),
child: ListTile(
contentPadding: const EdgeInsets.all(8),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
myDocs[index]['name'],
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
Card(
color: Colors.indigo,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
myDocs[index]['price'],
style: const TextStyle(
color: Colors.white,
fontStyle: FontStyle.italic,
fontSize: 20,
),
),
),
)
],
),
subtitle: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 12, 8),
child: Text(
myDocs[index]['description'],
style: const TextStyle(
fontSize: 18,
),
),
),
),
),
),
);
},
);
} catch (e) {
return const Center(
child: Card(
child: Text(
'Something went wrong, please check your connection',
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);

A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 'const'

const homeScreenItems = [
FeedScreen(),
SearchScreen(),
AddPostScreen(),
Text('notification'),
ProfileScreen(uid: FirebaseAuth.instance.currentUser!.uid),
];
above code is my global variable page.
I want to pass uid I stored in Firestore to ProfileScreen() but I am getting the above titled error i.e A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 'const'.
I have declared uid as final in my ProfileScreen() but still I am getting the above error
//here is the code of ProfileScreen()
class ProfileScreen extends StatefulWidget {
final String uid;
const ProfileScreen({Key? key,required this.uid}) : super(key: key);
#override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
var userData = {};
#override
void initState() {
getUserData();
super.initState();
}
getUserData() async {
try {
var snap = await FirebaseFirestore.instance
.collection('users')
.doc(widget.uid)
.get();
setState(() {
userData = snap.data()!;
});
} catch (e) {
showSnakBar(e.toString(), context);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: mobileBackgroundColor,
title: Text(userData['name']),
centerTitle: false,
),
body: ListView(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Row(
children: [
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
'https://images.unsplash.com/photo-1647185255712-b5b8687b2a25?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1722&q=80',
),
),
Expanded(
flex: 1,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: [
buildStatColumn(20, 'posts'),
buildStatColumn(150, 'followers'),
buildStatColumn(10, 'following'),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FollowButton(
backgroundColor: mobileBackgroundColor,
borderColor: Colors.grey,
text: 'Edit Profile',
textColor: primaryColor,
function: () {},
),
],
),
],
),
),
],
),
Container(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(top: 15),
child: Text(
'username',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
),
Container(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(top: 1),
child: Text('some bio'),
),
),
],
),
),
const Divider(),
],
),
);
}
Column buildStatColumn(int num, String lable) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
num.toString(),
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Container(
margin: const EdgeInsets.only(top: 4),
child: Text(
lable,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
),
],
);
}
}
The issue here is that you're using const in homeScreenItems - this sets the variable constant during compile-time and can't be changed. It's usually used for fixed values like Text widgets with fixed String values.
Also, utilizing the bang (!) operator doesn't guarantee that the value won't be null. This only assures the compiler that the value is not null.
Depending on your use-case, you can remove the const from homeScreenItems and add ProfileScreen() once the user has signed-in and you're able to fetch FirebaseAuth.instance.currentUser.
List homeScreenItems = [
FeedScreen(),
SearchScreen(),
AddPostScreen(),
Text('notification'),
];
...
if(FirebaseAuth.instance.currentUser != null){
homeScreenItems.add(ProfileScreen(uid: FirebaseAuth.instance.currentUser!.uid));
}

Retrieve same key data from Firebase on all pages

So the problem is I'm trying to retrieve this data from the Firebase database, where each case study
represent one key of data, and what I get is the same data of the first key on all the case study pages.
Data on the Firebase:
List of Case studies Page:
enter image description here
Case Study Page:
These are two different case studies yet have the same data.
enter image description here
enter image description here
I used Animated List at the beginning to retrieve the data but it gave me the same problem, so I
followed a Youtube Tutorial and used another way but the problem remains. I know I need to pass a key when the button is clicked to link each case study with its key but I'm not sure how.
Here is the code for more clarification:
stu_case_study_view.dart
Case Study Page
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:virtulab/Model/stu_case_study_model.dart';
import 'package:virtulab/functions/database.dart';
import 'package:virtulab/widgets/back_button.dart';
class CaseStudyView extends StatefulWidget {
final String csKey;
CaseStudyView({this.csKey});
#override
State<StatefulWidget> createState() {
return _CaseStudyView();
}
}
class _CaseStudyView extends State<CaseStudyView> {
bool _loading = false;
List<CaseStudyModel> caseStudyList = [];
final _formKey = GlobalKey<FormState>();
final question1Controller = TextEditingController();
final question2Controller = TextEditingController();
final question3Controller = TextEditingController();
final question4Controller = TextEditingController();
final question5Controller = TextEditingController();
DatabaseReference caseStudyInfo;
#override
void initState() {
super.initState();
caseStudyInfo = firebaseref.child('case_study');
caseStudyInfo.once().then((DataSnapshot snap) {
var keys = snap.value.keys;
var data = snap.value;
caseStudyList.clear();
for (var key in keys) {
CaseStudyModel csList = new CaseStudyModel(
data[key]['title'],
data[key]['description'],
data[key]['body'],
data[key]['question1'],
data[key]['question2'],
data[key]['question3'],
data[key]['question4'],
data[key]['question5'],
);
caseStudyList.add(csList);
}
setState(() {
print('Length : $caseStudyList.length');
});
});
}
#override
Widget build(BuildContext context) {
return
Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Case Study'), //Temp data
backgroundColor: Colors.deepPurple,
),
body: Container(
child: caseStudyList.length == 0
? new Text('No Case Studies Uploaded')
: new ListView.builder(
itemCount: caseStudyList.length,
itemBuilder: (_, index) {
return _caseStudy(
caseStudyList[index].title,
caseStudyList[index].description,
caseStudyList[index].body,
caseStudyList[index].question1,
caseStudyList[index].question2,
caseStudyList[index].question3,
caseStudyList[index].question4,
caseStudyList[index].question5,
);
}),
),
);
}
_showAlertDialog(BuildContext context) {
Widget cancelButton = FlatButton(
child: Text('Cancel'),
onPressed: () => Navigator.of(context, rootNavigator: true).pop());
Widget submitButton = FlatButton(
child: Text('Submit'),
onPressed: () {
if (_formKey.currentState.validate()) {
firebaseref.child('case_study').push().set({
"question1": question1Controller.text,
"question2": question2Controller.text,
"question3": question3Controller.text,
"question4": question4Controller.text,
"question5": question5Controller.text,
});
Navigator.of(context, rootNavigator: true).pop();
Navigator.pop(context);
}
},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text('Alert'),
content: Text('Are you sure you want to submit?'),
actions: [
cancelButton,
submitButton,
],
);
// show the dialog
showDialog(
context: context,
// barrierDismissible: false,
builder: (BuildContext cxt) {
return alert;
},
);
}
Widget _caseStudy(
String title,
String description,
String body,
String question1,
String question2,
String question3,
String question4,
String question5) {
return _loading
? Container(
child: Center(
child: CircularProgressIndicator(),
),
)
: Container(
padding: EdgeInsets.fromLTRB(10, 0, 10, 10),
child: Form(
key: _formKey,
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
child: ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: <Widget>[
Text(
title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
height: 2,
color: Colors.deepPurple),
),
Divider(),
Text(
'Description:',
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Text(
description,
textAlign: TextAlign.left,
maxLines: null,
),
),
Text(
'Case Study:',
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Text(
body,
textAlign: TextAlign.left,
maxLines: null,
),
),
Divider(),
Text(
'Questions:',
textAlign: TextAlign.left,
style: TextStyle(fontWeight: FontWeight.bold),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'1/ ' + question1,
textAlign: TextAlign.left,
maxLines: null,
),
],
)),
TextFormField(
controller: question1Controller,
validator: (v) =>
v.isEmpty ? 'Enter Your Answer' : null,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Write Your Answer Here',
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'2/ ' + question2,
textAlign: TextAlign.left,
maxLines: null,
),
],
)),
TextFormField(
controller: question2Controller,
validator: (v) =>
v.isEmpty ? 'Enter Your Answer' : null,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Write Your Answer Here',
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'3/ ' + question3,
textAlign: TextAlign.left,
maxLines: null,
),
],
)),
TextFormField(
controller: question3Controller,
validator: (v) =>
v.isEmpty ? 'Enter Your Answer' : null,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Write Your Answer Here',
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'4/ ' + question4,
textAlign: TextAlign.left,
maxLines: null,
),
],
)),
TextFormField(
controller: question4Controller,
validator: (v) =>
v.isEmpty ? 'Enter Your Answer' : null,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Write Your Answer Here',
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'5/ ' + question5,
textAlign: TextAlign.left,
maxLines: null,
),
],
)),
TextFormField(
controller: question5Controller,
validator: (v) =>
v.isEmpty ? 'Enter Your Answer' : null,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Write Your Answer Here',
),
),
Align(
alignment: Alignment.centerRight,
child: Container(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
children: <Widget>[
FloatingActionButton.extended(
onPressed: () {
_showAlertDialog(context);
},
label: Text(
"Submit",
style: TextStyle(
fontWeight: FontWeight.bold),
),
backgroundColor: Colors.amber,
),
],
))),
),
]),
)));
}
}
stu_case_study_model.dart
class CaseStudyModel {
String title,
description,
body,
question1,
question2,
question3,
question4,
question5;
CaseStudyModel(this.title, this.description, this.body, this.question1,
this.question2, this.question3, this.question4, this.question5);
}
stu_caseStudies_list.dart
List of Case studies Page
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:virtulab/functions/Student/class_case_study_list.dart';
import 'package:virtulab/functions/database.dart';
import 'package:virtulab/student/stu_case_study_view.dart';
class CaseStudiesList extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _CaseStudiesList();
}
}
class _CaseStudiesList extends State<CaseStudiesList> {
Query _caseStudyTitle;
#override
void initState() {
super.initState();
_caseStudyTitle = firebaseref.child('case_study');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Case Studies'),
backgroundColor: Colors.deepPurple,
),
body: FirebaseAnimatedList(
query: _caseStudyTitle,
defaultChild: Center(child: CircularProgressIndicator()),
itemBuilder: (BuildContext context, snapshot,
Animation<double> animation, int index) {
Map caseStudy = snapshot.value;
caseStudy['key'] = snapshot.key;
return _caseStudyList(caseStudy: caseStudy);
},
),
);
}
Widget _caseStudyList({Map caseStudy}) {
return Column(
children: [
Card(
child: InkWell(
onTap: () {},
child: Container(
margin: EdgeInsets.symmetric(vertical: 10),
// padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
// height: 70,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(
Icons.description_sharp,
),
SizedBox(width: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
caseStudy['title'],
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
height: 2,
color: Colors.deepPurple),
),
],
),
],
),
ElevatedButton(
onPressed: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CaseStudyView(
//csKey: caseStudy['key'],
),
),
)
},
child: Text('Start'),
// color: Colors.amber,
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.amber))),
],
),
),
SizedBox(height: 5),
],
),
),
),
),
],
);
}
}
This is my graduation project and I sincerely appreciate your help. Thank you.

Flutter:How to convert Cards UI or View to Individual View Please find the HomeScreen Page code and try to convert to detailed individual view

Flutter:How to convert Cards UI or View to Individual View Please find the HomeScreen Page code and try to convert to detailed individual view
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:gadjet_inventory/Form/ListTiles.dart';
import 'package:gadjet_inventory/main.dart';
import 'package:intl/intl.dart';
import 'package:gadjet_inventory/Form/Data.dart';
import 'UploadData.dart';
import 'package:pdf_flutter/pdf_flutter.dart';
// ignore: must_be_immutable
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<Data> dataList = [];
List<bool> favList = [];
bool searchState = false;
FirebaseAuth auth = FirebaseAuth.instance;
#override
void initState() {
// TODO: implement initState
super.initState();
DatabaseReference referenceData = FirebaseDatabase.instance.reference().child("Data");
referenceData.once().then((DataSnapshot dataSnapShot) {
dataList.clear();
favList.clear();
var keys = dataSnapShot.value.keys;
var values = dataSnapShot.value;
for (var key in keys) {
Data data = new Data(
values [key]['imgUrl'],
values [key]['wcpdfUrl'],
values [key]['ugpdfUrl'],
values [key]['cattegorrytype'],
values [key]['companyname'],
values [key]['modelname'],
values [key]['seriesname'],
values [key]['year'],
key
//key is the uploadid
);
dataList.add(data);
auth.currentUser().then((value) {
DatabaseReference reference = FirebaseDatabase.instance.reference().child("Data").child(key).child("Fav")
.child(value.uid).child("state");
reference.once().then((DataSnapshot snapShot){
if(snapShot.value!=null){
if(snapShot.value=="true"){
favList.add(true);
}else{
favList.add(false);
}
}else{
favList.add(false);
}
});
});
}
Timer(Duration(seconds: 1),(){
setState(() {
//
});
});
});
}
int selectedRadioTile;
String get path => null;
String get title => null;
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreen,
//Color(0xffffffff),
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.blue,
title: new Text("Device Details", style:
TextStyle(fontSize: 20), textAlign: TextAlign.center),
actions: <Widget>[
IconButton(icon: Icon(Icons.refresh, size: 36, color: Colors.white,),
onPressed: () {
//debugPrint("Add New Device Cattegorry");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ListTiles();
}
)
); //
},
),
IconButton(icon: Icon(Icons.home, size: 36, color: Colors.white,),
onPressed: () {
//debugPrint("Add New Device Cattegorry");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return MyHomePage();
}
)
); //
},
)
],),
body: dataList.length == 0
? Center(
child: Text("No Data Available", style: TextStyle(fontSize: 30),))
: ListView.builder(
itemCount: dataList.length,
itemBuilder: (_, index) {
return CardUI(dataList[index].imgUrl,dataList[index].wcpdfUrl, dataList[index].cattegorrytype,
dataList[index].companyname, dataList[index].modelname,dataList[index].seriesname,dataList[index].year,
dataList[index].uploadid,index);
}
),
);
}
Widget CardUI(String imgUrl, String wcpdfUrl,String cattegorrytype, String companyname, String modelname,
String seriesname, String year ,
String uploadId,int index) {
return Card(
elevation: 7,
margin: EdgeInsets.all(15),
//color: Color(0xffff2fc3),
color:Colors.blueGrey,
child: Container(
color: Colors.white,
margin: EdgeInsets.all(1.5),
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Image.network(
imgUrl != null
? imgUrl
: '',
width: 500,
height: 500,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text( "Cattegorry Type:- "
"$cattegorrytype",
style: TextStyle(color: Colors.black),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Company Name:- "
"$companyname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Model Name:- "
"$modelname",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Series Name:- "
"$seriesname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Year Of MFG:- "
"$year",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.blue,
child: Text("Warranty Card",
style: TextStyle(fontSize: 18, color: Colors.white),),
),
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text("PDF"),
//subtitle: Text("Upload PDF File"),
/* onChanged: (val) {
filePicker(context);
},*/
activeColor: Colors.red,
),
Padding(padding: EdgeInsets.only(top: 15)),
// _buildPDF1Field(context),
PDF.network(
wcpdfUrl != null
? wcpdfUrl
: '',
width: 600,
height: 1000, placeHolder: Image.asset("assets/images/pdf.png",
height: 600, width: 500),
),
SizedBox(height: 24),
],
),
),
);
}
I have uploaded few text items one imageUrl and one pdf document to firebase storage and able to retrieve them in HomeScreen View (card UI or View (cards list) and List Tile View( with one image and one text, when tapped on it should show each individual view).
Please guide me How to convert to Individual Retrieving page instead of group of vertical cards list.

Download data from firebase Firestore to flutter

I am using Firestore as a database for a Chat in one part of the application that I am building. I have a collection on my Firestore that looks like this:
messages(collection)
userId
userId-otherUserId(sub-collection)
randomId
content : String,
timestamp : Date
...
and I would like to retrieve firstly all of the userIs-otherUserId in a ListView and then to retrieve the lastMessage by retrieving the last randomId(and in that randomId the last message is the last element with key 'content') and I would like it to look something like this.
Prototype
where the Loading represents last message but the name and profilePicture I can get from my API.
The pictures of my Firestore database:
First Image
Second Image
Third Image
Is there any chance that I could save the name and Profile picture on the database in the userId-otherUserId(collection)?
The code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:disby_app/const.dart';
import 'package:disby_app/data/request_model.dart';
import 'package:disby_app/global_widgets/loading_indicator.dart';
import 'package:disby_app/main_screens/main_chat_and_request_screens/chat.dart';
import 'package:disby_app/main_screens/main_chat_and_request_screens/profile_details_screen.dart';
import 'package:disby_app/public/keys.dart';
import 'package:disby_app/services/json_requests.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../global_widgets/chat_and_requests_placeholder.dart';
class MainChatScreen extends StatefulWidget {
#override
_MainChatScreenState createState() => _MainChatScreenState();
}
class _MainChatScreenState extends State<MainChatScreen> {
bool _areThereChats = false;
bool _isLoading = true;
String groupChatId;
String userId = '1';
List<String> listOfLastMessages = [];
List<String> listOfIds = [];
List<ArrayOfRequestsModel> arrayOfRequests = [];
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
Future readLocal() async {
var prefs = await SharedPreferences.getInstance();
userId = prefs.getString(kUserId) ?? '';
print(userId);
setState(() {});
}
Future<void> _getRequests() async {
final prefs = await SharedPreferences.getInstance();
final userId = prefs.getString(kUserId);
try {
await Dio().post(baseUrl + acceptedUsers + "/" + userId).then((snapshot) {
print(snapshot);
final Map<String, dynamic> response = snapshot.data;
print(response);
if (response['response'] == 'success') {
List<dynamic> arrayFromServer = response['acceptedUsers'];
if (arrayFromServer.isNotEmpty) {
arrayFromServer.forEach((userData) {
arrayOfRequests.add(ArrayOfRequestsModel.fromJson(userData));
listOfIds.add(userData['userId']);
print(userData['userId']);
});
_areThereChats = true;
_isLoading = false;
getMessages(userId);
} else {
_areThereChats = false;
_isLoading = false;
}
setState(() {});
} else {
_areThereChats = false;
_isLoading = false;
setState(() {});
}
});
} catch (e) {
print(e);
}
}
getMessages(String userId) {
int i = 0;
print(listOfIds.length);
print(listOfIds);
listOfIds.forEach((element) {
Firestore.instance
.collection('messages')
.document('$userId')
.collection('$userId-$element')
.orderBy('timestamp', descending: true)
.limit(3)
.getDocuments()
.then((QuerySnapshot snapshot) {
print(snapshot.documents[0].data['content']);
snapshot.documents.forEach((f) {
print(f.data['content']);
listOfLastMessages.add(f.data['content']);
setState(() {});
i++;
});
if (i == listOfIds.length) {
setState(() {});
print(listOfLastMessages);
}
});
});
}
#override
void initState() {
readLocal();
_getRequests();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Container(
width: double.infinity,
height: double.infinity,
child: SingleChildScrollView(
// child: (userId != '1')
// ? StreamBuilder(
// stream: Firestore.instance
// .collection('messages')
// .document('5ef4d83175b07cf074525c08')
// .snapshots(),
// builder: (context, snapshot) {
// // if (snapshot.hasData) {
// if (!snapshot.hasData) {
// return Center(
// child: CircularProgressIndicator(
// valueColor: AlwaysStoppedAnimation<Color>(themeColor),
// ),
// );
// } else {
// return Container(
// width: 100,
// height: 200,
// child: ListView.builder(
// padding: EdgeInsets.all(10.0),
// itemBuilder: (context, index) =>
// buildItem(context, snapshot.data.documents),
// itemCount: snapshot.data.documents.length,
// ),
// );
// }
// },
// )
// : LoadingIndicator(
// loading: _isLoading,
// ),
// ),
child: Column(
children: <Widget>[
(_isLoading == false)
? (_areThereChats == true)
? Container(
child: AnimatedList(
key: _listKey,
shrinkWrap: true,
initialItemCount: arrayOfRequests.length,
itemBuilder:
(BuildContext context, index, animation) {
return _buildItem(context, arrayOfRequests[index],
animation, index);
},
),
)
: ChatAndRequestPlaceholder(
text: translate('when_someone_sends_you_a_request'))
: LoadingIndicator(
loading: _isLoading,
),
],
),
),
),
);
}
Widget buildItem(BuildContext context, DocumentSnapshot document) {
if (document['id'] == userId) {
return Container();
} else {
return Container(
child: FlatButton(
child: Row(
children: <Widget>[
Flexible(
child: Container(
child: Column(
children: <Widget>[
Container(
child: Text(
'Nickname: ${document['content']}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
),
Container(
child: Text(
'About me: ${document['content'] ?? 'Not available'}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0),
)
],
),
margin: EdgeInsets.only(left: 20.0),
),
),
],
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: document.documentID,
peerAvatar: document['photoUrl'],
),
),
);
},
color: greyColor2,
padding: EdgeInsets.fromLTRB(25.0, 10.0, 25.0, 10.0),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
),
margin: EdgeInsets.only(bottom: 10.0, left: 5.0, right: 5.0),
);
}
}
_buildItem(BuildContext context, ArrayOfRequestsModel arrayOfSentRequests,
Animation animation, int index) {
return GestureDetector(
onTap: () {
print(arrayOfSentRequests.profilePictureUrl);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: arrayOfSentRequests.userId,
peerAvatar: arrayOfSentRequests.profilePictureUrl,
),
),
);
},
child: Container(
height: 82,
child: ScaleTransition(
scale: animation,
child: Padding(
padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, 0.07),
offset: Offset(0, 5),
blurRadius: 11,
),
],
),
width: double.infinity,
height: 78,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Container(
height: double.infinity,
child: GestureDetector(
onTap: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(
builder: (context) => ProfileDetailsScreen(),
),
);
},
child: Row(
children: <Widget>[
SizedBox(width: 24),
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Image(
image: NetworkImage(
arrayOfSentRequests.profilePictureUrl,
),
width: 48,
),
),
SizedBox(width: 10),
Expanded(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
arrayOfSentRequests.nameAndSurname,
style: TextStyle(
color: Colors.black,
fontFamily: 'Avenir',
fontWeight: FontWeight.w700,
fontSize: 18,
),
),
Text(
'11/11/2020', //arrayOfSentRequests.nameAndSurname
style: TextStyle(
color: Colors.grey,
fontFamily: 'Avenir',
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
],
),
),
Container(
child: Text(
// (arrayOfSentRequests.lastMessage !=
// null)
// ? arrayOfSentRequests.lastMessage
// : 'Loading..',
(listOfLastMessages.isNotEmpty)
? listOfLastMessages[index]
.toString()
: 'Loading...',
maxLines: 2,
softWrap: true,
style: TextStyle(
color: Colors.black54,
fontFamily: 'Avenir',
fontSize: 15,
),
),
),
],
),
),
),
SizedBox(width: 10),
],
),
),
),
),
Container(
child: Center(
child: Icon(
Icons.keyboard_arrow_right,
size: 22,
color: Colors.black54,
),
),
),
SizedBox(width: 10),
],
),
),
),
),
),
);
}
}

Resources