I can't access uid from firebase. I tried so many times. can anyone help me with this issue?
class Massages extends StatelessWidget {
#override Widget build(BuildContext context) {
return FutureBuilder(
future: Future.value(FirebaseAuth.instance.currentUser),
builder: (ctx, futureSnapshot) {
if (futureSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chat')
.orderBy('createdAt', descending: true)
.snapshots(),
builder: (ctx, AsyncSnapshot<dynamic> chatSnapshot) {
if (chatSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
reverse: true,
itemCount: chatSnapshot.data!.docs.length,
itemBuilder: (ctx, index) => MessageBubble(
chatSnapshot.data!.docs[index]['text'],
chatSnapshot.data!.docs[index]['userId'] ==
futureSnapshot.data?.uid,
key: ValueKey(chatSnapshot.data!.documentID),
),
);
});
}); } }
It looks like futureSnapshot.data returns an Object rather than a User. You could try casting it to the correct type with:
((User)futureSnapshot.data)?.uid,
Related
I am struggling to resolve these two errors.
error: The property 'docs' can't be unconditionally accessed because the receiver can be 'null'. (unchecked_use_of_nullable_value at [church_app] lib\Screens\DevotionalList.dart:23)
error: The parameter 'devotional' can't have a value of 'null' because of its type, but the implicit default value is 'null'. (missing_default_value_for_parameter at [church_app] lib\Screens\DevotionalList.dart:39)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class DevotionalList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('devotionals').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text('Error: ${snapshot.error}'),
);
}
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
// Use the .docs property to access the list of documents.
List<DocumentSnapshot> documents = snapshot.data.docs;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (context, index) {
DocumentSnapshot devotional = documents[index];
return DevotionalTile(devotional: devotional);
},
);
},
);
}
}
class DevotionalTile extends StatelessWidget {
final DocumentSnapshot devotional;
DevotionalTile({this.devotional});
#override
Widget build(BuildContext context) {
if (devotional == null) {
return Container();
}
return ExpansionTile(
title: Text(devotional['title']),
subtitle: Text('By ${devotional['author']}'),
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(devotional['body']),
),
],
);
}
}
Any assistance would be appreciated.
Tried adding null exceptions but I still run into the same error.
at the point when your call snapshot.data.docs, it can't be null since you checked first with the hasError, so you can tell this to Dart by explicitly adding a !, instead of this:
List<DocumentSnapshot> documents = snapshot.data.docs;
add !, so it will be this:
List<DocumentSnapshot> documents = snapshot.data.docs!;
this will fix both the error you're facing.
I have future function and I want show this in the listview.seprator, but the listview do not get the future value. how can i fix this?
this is my code:
my hive class:
#HiveType(typeId: 3)
class TaskCat extends HiveObject{
#HiveField(0)
String catName;
#HiveField(1)
int userId;
#HiveField(2)
User? user;
TaskCat(this.catName,this.user,this.userId);
}
This is my function:
Future<List> showCategoryInHome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskCatBox = await Hive.openBox('taskCat');
var filtertaskCat = taskCatBox.values
.where(
(TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
.toList();
return filtertaskCat;
}
and this is my listview code:
FutureBuilder(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
Future<List> test = controller.showCategoryInHome();
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: 11 , // here currently I set the fix value but I want the length of my list
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
},
child: Text(
test[index].[catName], // and here not working too bucouse the list is future
style: normalTextForCategory,
),
);
},
separatorBuilder:
(BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
},
)
Try this:
FutureBuilder<List>(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount:data.length,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {},
child: Text(
data[index]['catName'],
style: normalTextForCategory,
),
);
},
separatorBuilder: (BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
}
}
},
),
Inside your Future you have builder, where you can access to your future when it ready via snapshot.
I've added the precise type where to make the use of Futurebuilder easier.
Future<List<TaskCat>> showCategoryInHome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskCatBox = await Hive.openBox('taskCat');
var filtertaskCat = taskCatBox.values
.where(
(TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
.toList();
return filtertaskCat;
}
And adjust your Futurebuilder to the following:
FutureBuilder<List<TaskCat>>(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
// Check if your future has finished
if(snapshot.hasData) {
// Here you have the result of your future, which is a List<TaskCat>
final tasks = snapshot.data;
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: tasks.length,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
},
child: Text(
tasks[index].catName,
style: normalTextForCategory,
),
);
},
separatorBuilder:
(BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
} else {
// Here you can show e.g. a CircularProgressIndicator
return SizedBox();
}
},
)
I want to make a to-do list with task due date as an optional field, so I need to check if some tasks have dueDate and add it as a subtitle based on that. How can I check if a field exists inside a doc in a StreamBuilder?
class _TaskListState extends State<TaskList> {
var myStream;
#override
void initState() {
myStream = FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.snapshots();
super.initState();
}
...
void _updateTaskDesc(
dynamic currTask, String newDesc, DateTime newDate, TimeOfDay newTime) {
FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.doc(currTask['id'])
.update({
'desc': newDesc,
'dueDate': newDate.toString(),
'dueTime': newTime.toString(),
});
}
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: myStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: SizedBox(
height: 100, width: 100, child: CircularProgressIndicator()),
);
} else {
final docs = snapshot.data.docs;
bool hasDateTime = ????? <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return ListView.builder(
itemCount: docs.length,
itemBuilder: (ctx, index) {
final currTask = docs[index];
return InkWell(
highlightColor: Theme.of(context).secondaryHeaderColor,
splashColor: Theme.of(context).secondaryHeaderColor,
onLongPress: () {
showModalBottomSheet<dynamic>(
isScrollControlled: true,
context: context,
builder: (bCtx) {
FocusManager.instance.primaryFocus?.unfocus();
return TaskOptions(_updateTaskDesc,
() => _updateHasImage(docs[index]), currTask);
},
);
},
child: Dismissible(
direction: DismissDirection.startToEnd,
key: UniqueKey(),
onDismissed: (_) async {
FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.doc(currTask['id'])
.delete();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("${currTask['desc']} dismissed"),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
FirebaseFirestore.instance
.collection("tasks")
.doc(widget.uid)
.collection("mytasks")
.doc(currTask['id'])
.set({
"desc": currTask['desc'],
"id": currTask['id'],
"isDone": currTask['isDone'],
"hasImage": currTask['hasImage'],
});
try {
FirebaseFirestore.instance
.collection("tasks")
.doc(widget.uid)
.collection("mytasks")
.doc(currTask['id'])
.update({
"dueDate": currTask['dueDate'],
"dueTime": currTask['dueTime'],
});
} catch (e) {}
},
),
),
);
},
child: ListTile(
...
subtitle: Text(hasDateTime
? DateFormat('dd/MM')
.format(DateTime.parse(currTask['dueDate']))
: ''),
...
I saw that a containsKey('key') method works for some people but I get NoSuchMethod when I try that. What can I do?
The single document is just a normal Dart Map, so you can check if a key exists or not using containsKey method.
So you condition becomes the following:
bool hasDateTime = currTask.containsKey('dueDate`);
NOTE: In the question I can see that you are defining the condition in the wrong place which is outside the itemBuilder method in the ListView so that it is not item based and well not work because it does not make sense.
You can have it in this place:
...
itemBuilder: (ctx, index) {
final currTask = docs[index];
bool hasDateTime = currTask.containsKey('dueDate`);
return InkWell(
...
I am using ubuntu other projects can be excuted most of the bluetooth functionalities are not working.
The snapshot.data is always an empty array even though there are so many active devices and I am using vs code ubuntu and flutter_blue package. I tested it on many devices and its not working even the example they gave is not working.
Is the problem with my ubuntu system or someone else has the problem with the same example they have on git ?
https://github.com/pauldemarco/flutter_blue
class FindDevicesScreen extends StatefulWidget {
FindDevicesScreen({Key key}) : super(key: key);
#override
_FindDevicesScreenState createState() => _FindDevicesScreenState();
}
class _FindDevicesScreenState extends State<FindDevicesScreen> {
#override
void initState() {
// TODO: implement initState
super.initState();
FlutterBlue.instance.startScan(timeout: Duration(seconds: 4));
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
RaisedButton(
onPressed: () {
FlutterBlue.instance.startScan(timeout: Duration(seconds: 4));
},
child: Text("Search"),
),
StreamBuilder<List<BluetoothDevice>>(
stream: Stream.periodic(Duration(seconds: 2))
.asyncMap((_) => FlutterBlue.instance.connectedDevices),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
print('connection active');
}
if (snapshot.hasData) {
return Column(children: [
Text("There is data"),
Text(snapshot.data.length.toString())
]);
} else if (snapshot.hasError) {
print("Error");
return Center(
child: Text("There is some error"),
);
} else {
return Center(
child: Text("Nodata"),
);
}
}),
Divider(),
StreamBuilder<List<ScanResult>>(
stream: FlutterBlue.instance.scanResults,
builder: (context, snapshot) {
if (snapshot.hasData) {
print("inside checking");
print(snapshot.data);
return Text(snapshot.data.length.toString());
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else {
return Text("No data");
}
}),
],
)),
);
}
}
I have a graph view my app, whenever my function works it's also rebuilding
how to control my UI
var response = await getdashboarddata(tokenkey);
setState(() {
});
use FutureBuilder
Widget projectWidget() {
return FutureBuilder(
builder: (context, projectSnap) {
if (projectSnap.connectionState == ConnectionState.none &&
projectSnap.hasData == null) {
//print('project snapshot data is: ${projectSnap.data}');
return Container();
}
return ListView.builder(
itemCount: projectSnap.data.length,
itemBuilder: (context, index) {
ProjectModel project = projectSnap.data[index];
return Column(
children: <Widget>[
// Widget to display the list of project
],
);
},
);
},
future: getdashboarddata(tokenkey),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ProjectList'),
),
body: projectWidget(),
);
}