I wanted to make a looping URL with firebase. I use this fucntion to get the url from my firebase.
class getUri extends StatelessWidget {
final String documentId;
getUri({required this.documentId});
@override
Widget build(BuildContext context) {
//get collection
CollectionReference umum = FirebaseFirestore.instance.collection('umum');
return FutureBuilder<DocumentSnapshot>(
future: umum.doc(documentId).get(),
builder: ((context, snapshot){
if(snapshot.connectionState==ConnectionState.done){
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return Text('${data['url']}');
}
return Text('loading...');
}
)
);
}
}
but I can't get it to run on my code
Expanded(
child: FutureBuilder(
future: umum(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: docID.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(docID[index]),
onTap: () {
launchUrl(
Uri.parse(getUri(documentId: docId[index])),
mode: LaunchMode.externalApplication
);
},
);
}
);
}
)
)
The error said "Error: The argument type 'getUri' can't be assigned to the parameter type 'String'"
I tried adding cast on the getUri but it gave me this error "The following _CastError was thrown while handling a gesture: type 'getUri' is not a subtype of type 'String' in type cast"
Uri.parse(getUri(documentId: docID[index]) as String)
You are defining getUri
as a StatelessWidget
, not function. To define getUri
as a function, do it like this:
Future<String> getUri({required String documentId}) async {
final umum = FirebaseFirestore.instance.collection('umum');
final snapshot = await umum.doc(documentId).get();
Map<String, dynamic> data = snapshot.data() as Map<String, dynamic>;
return data['url'];
}
You can then use the function like this:
onTap: () async {
launchUrl(
Uri.parse(await getUri(documentId: docId[index])), // use await keyword here
mode: LaunchMode.externalApplication
);
}
This should fix the problems to your code. However, I recommend following the usage instructions from the Firestore official documentation, and add a proper error handling as well.