Skip to content

Instantly share code, notes, and snippets.

@crazy-diya
Created October 30, 2022 10:55
Show Gist options
  • Save crazy-diya/c8ac2a0466c279d0de1459f947e1e21e to your computer and use it in GitHub Desktop.
Save crazy-diya/c8ac2a0466c279d0de1459f947e1e21e to your computer and use it in GitHub Desktop.
Work with FutureBuilder and ListView.Builder synchronosly Dart Flutter
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:material_floating_search_bar/material_floating_search_bar.dart';
import 'package:syncoios_beta/DJEvents/calender_view.dart';
import 'package:syncoios_beta/DJEvents/entities/event_entity.dart';
import 'package:syncoios_beta/DJEvents/event_desc_view.dart';
class EventView extends StatefulWidget {
const EventView({Key? key}) : super(key: key);
@override
State<EventView> createState() => _EventViewState();
}
class _EventViewState extends State<EventView> {
List<EventEntity> shows = [];
List<EventEntity> showsList = [];
bool clicked = false;
Position? position;
Placemark? _place;
@override
void initState() {
super.initState();
_determinePosition();
loadShows();
}
Widget buildFloatingSearchBar(double height, double width) {
final isPortrait =
MediaQuery.of(context).orientation == Orientation.portrait;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: FloatingSearchBar(
margins: const EdgeInsets.all(8),
padding: const EdgeInsets.only(right: 12, left: 12),
hint: 'Name / Country / State / Place ..',
backdropColor: Colors.transparent,
scrollPadding: const EdgeInsets.only(top: 16, bottom: 56),
transitionDuration: const Duration(milliseconds: 800),
transitionCurve: Curves.easeInOut,
physics: const BouncingScrollPhysics(),
axisAlignment: isPortrait ? 0.0 : -1.0,
openAxisAlignment: 0.0,
borderRadius: const BorderRadius.all(Radius.circular(20)),
width: isPortrait ? 600 : 500,
debounceDelay: const Duration(milliseconds: 500),
onQueryChanged: (query) {
searchShow(query);
},
transition: CircularFloatingSearchBarTransition(),
automaticallyImplyDrawerHamburger: false,
automaticallyImplyBackButton: false,
onFocusChanged: (value) {
debugPrint("Clicked");
setState(() {
clicked = true;
});
},
actions: [
FloatingSearchBarAction(
showIfOpened: false,
child: CircularButton(
padding: EdgeInsets.zero,
icon: const Icon(Icons.place),
onPressed: () {},
),
),
FloatingSearchBarAction.searchToClear(
showIfClosed: false,
),
],
builder: (context, transition) {
return ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
height: height * 0.8,
child: showsList.isEmpty
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: showsList.length,
itemBuilder: (context, index) {
DateTime date = DateTime.fromMillisecondsSinceEpoch(
int.parse(
showsList[index].time!,
),
);
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDescView(
eventData: showsList[index],
),
),
);
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
margin: const EdgeInsets.only(bottom: 10),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
contentPadding:
const EdgeInsets.only(left: 0),
leading: Container(
width: 65,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: NetworkImage(
showsList[index].image!),
fit: BoxFit.fitHeight,
),
),
),
title: Text(
showsList[index].showName!,
style: const TextStyle(
fontWeight: FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
showsList[index].description!,
maxLines: 1,
style: DefaultTextStyle.of(context)
.style,
),
Text(
showsList[index].state!,
maxLines: 1,
)
],
),
trailing: Column(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(DateFormat('yyyy-MM-dd')
.format(date)
.toString()),
const SizedBox(
height: 4,
),
SizedBox(
width: 43,
child: Row(children: [
Container(
margin: const EdgeInsets.only(
right: 8),
child: Image.asset(
"assets/images/participate.png",
height: 18,
width: 18,
),
),
Text(
showsList[index]
.noOfGoing
.toString(),
style: const TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 14),
)
]),
),
],
),
),
),
),
);
},
),
),
);
},
),
),
],
);
}
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: const Text("Events List"),
automaticallyImplyLeading: true,
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.calendar_month),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const CalenderView(),
),
);
},
backgroundColor: Colors.green),
body: SafeArea(
child: Container(
color: Colors.grey.shade900,
padding: const EdgeInsets.all(08),
child: Column(
children: [
Expanded(
child: buildFloatingSearchBar(height, width),
),
!clicked
? Expanded(
flex: 8,
child: FutureBuilder<List<EventEntity>>(
future: _loadData(),
builder: (BuildContext context,
AsyncSnapshot<List<EventEntity>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Center(
child: Text(
'Loading....',
style: TextStyle(color: Colors.white),
),
);
default:
if (snapshot.data == null ||
snapshot.data!.isEmpty) {
return const Center(
child: Text(
"In your area doesn't have any shows. Please Search ..",
style: TextStyle(color: Colors.white),
),
);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: 08),
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
DateTime date =
DateTime.fromMillisecondsSinceEpoch(
int.parse(
showsList[index].time!,
),
);
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
EventDescView(
eventData:
snapshot.data![index],
),
),
);
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10),
),
margin:
const EdgeInsets.only(bottom: 10),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
contentPadding:
const EdgeInsets.only(
left: 0),
leading: Container(
width: 65,
decoration: BoxDecoration(
color: Colors.red,
borderRadius:
BorderRadius.circular(10),
image: DecorationImage(
image: NetworkImage(snapshot
.data![index].image!),
fit: BoxFit.fitHeight,
),
),
),
title: Text(
snapshot.data![index].showName!,
style: const TextStyle(
fontWeight:
FontWeight.bold),
),
subtitle: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
snapshot.data![index]
.description!,
maxLines: 1,
style: DefaultTextStyle.of(
context)
.style,
),
Text(
snapshot
.data![index].state!,
maxLines: 1,
)
],
),
trailing: Column(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(DateFormat('yyyy-MM-dd')
.format(date)
.toString()),
const SizedBox(
height: 4,
),
SizedBox(
width: 43,
child: Row(children: [
Container(
margin: const EdgeInsets
.only(right: 8),
child: Image.asset(
"assets/images/participate.png",
height: 18,
width: 18,
),
),
Text(
snapshot.data![index]
.noOfGoing
.toString(),
style: const TextStyle(
color: Colors.green,
fontWeight:
FontWeight.bold,
fontSize: 14),
)
]),
),
],
),
),
),
),
);
});
}
}
},
),
)
: const SizedBox.shrink()
],
),
),
),
);
}
void searchShow(String query) {
setState(() {
showsList = shows;
});
var suggestion = showsList.where((show) {
var showName = show.showName!.toLowerCase();
var showCity = show.country!.toLowerCase();
var showState = show.state!.toLowerCase();
var showPlace = show.eventPlace!.toLowerCase();
var input = query.toLowerCase();
if (showName.contains(input) == true) {
return showName.contains(input);
} else if (showCity.contains(input) == true) {
return showCity.contains(input);
} else if (showState.contains(input) == true) {
return showState.contains(input);
} else if (showPlace.contains(input) == true) {
return showPlace.contains(input);
} else {
return false;
}
}).toList();
setState(() {
showsList = suggestion;
});
}
void loadShows() async {
await FirebaseFirestore.instance.collection("Events").get().then((event) {
for (var element in event.docs) {
setState(() {
shows.add(EventEntity.fromJson(element.data()));
});
}
shows.sort(
(a, b) => int.parse(a.time.toString())
.compareTo(int.parse(b.time.toString())),
);
setState(() {
showsList = shows.reversed.toList();
});
});
}
Future<List<EventEntity>> _loadData() async {
List<EventEntity> posts = [];
await FirebaseFirestore.instance.collection("Events").get().then((event) {
for (var element in event.docs) {
if (element.data()["country"] == _place!.country ||
element.data()["state"] == _place!.locality ||
element.data()["state"] == _place!.subAdministrativeArea) {
posts.add(EventEntity.fromJson(element.data()));
}
}
});
return posts;
}
Future<void> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
await Geolocator.openLocationSettings();
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
position = await Geolocator.getCurrentPosition();
List<Placemark> placemark =
await placemarkFromCoordinates(position!.latitude, position!.longitude);
setState(() {
_place = placemark[0];
});
print(placemark);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment