How to get image from API to Carousel in Flutter - flutter

I am facing this problem where I am trying to display images in a carousel. I am using the package carousel_slider: ^4.1.1. I am confused because when I hard code the content in a variable it is working perfectly displayed in my carousel widget. but the output is empty I want to use a Carousel in Flutter, so I tried to get it following the code. after running my code it's empty in output.
Map mapResponse = {};
Map dataResponse = {};
List listResponse = {} as List;
class apipro extends StatefulWidget {
const apipro({Key? key}) : super(key: key);
#override
State<apipro> createState() => _apipro();
}
class _apipro extends State<apipro> {
Future<List> team() async {
http.Response response;
response = await http.get(Uri.parse(
"https://www.archmage.lk/api/v1/webapi/getclients?page=0&limit=10"));
// ignore: unnecessary_null_comparison
Map mapResponse = json.decode(response.body);
return mapResponse['data'] as List;
}
#override
void initState() {
// team();
super.initState();
}
#override
Widget build(BuildContext context) {
return Center(
child: FutureBuilder<List?>(
future: team(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text(
'Loading....',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w100,
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
_buildItem(image, String name) {
return CarouselSlider(
options: CarouselOptions(
viewportFraction: 0.3,
autoPlayAnimationDuration:
const Duration(milliseconds: 2000),
autoPlay: true,
enlargeCenterPage: true,
height: 80),
items: <Widget>[
for (var i = 0; i < image.length; i++)
Container(
margin:
const EdgeInsets.only(top: 20.0, left: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(image[i]),
fit: BoxFit.fitHeight,
),
// border:
// Border.all(color: Theme.of(context).accentColor),
borderRadius: BorderRadius.circular(32.0),
),
),
],
);
// ignore: dead_code
}
return ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.all(18),
itemBuilder: (context, index) {
return _buildItem(data[index]['name']?.toString() ?? '',
data[index]['image']?.toString() ?? '');
},
itemCount: data.length,
);
}
}
}),
);
}
}
I got the Proper response by Function which I created there is no error in my code. So how i can display Images in carousel_slider? Please Help. Thank you.

Try this:
Center(
child: FutureBuilder<List?>(
future: team(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text(
'Loading....',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w100,
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return CarouselSlider.builder(
itemBuilder: (context, index, realIndex) {
return Container(
margin: const EdgeInsets.only(top: 20.0, left: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(data[index]['image']),
fit: BoxFit.fitHeight,
),
color: Colors.red,
borderRadius: BorderRadius.circular(32.0),
),
);
},
options: CarouselOptions(
viewportFraction: 0.3,
autoPlayAnimationDuration:
const Duration(milliseconds: 2000),
autoPlay: true,
enlargeCenterPage: true,
height: 80),
itemCount: data.length,
);
}
}
}),
)

class APIPRO extends StatelessWidget {
const APIPRO({Key? key}) : super(key: key);
Future<List> team() async {
http.Response response;
response = await http.get(Uri.parse("https://www.archmage.lk/api/v1/webapi/getclients?page=0&limit=10"));
// ignore: unnecessary_null_comparison
Map mapResponse = jsonDecode(response.body);
return mapResponse['data'] as List;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder(
future: team(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text(
'Loading....',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w100,
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return CarouselSlider(
options: CarouselOptions(viewportFraction: 0.3, autoPlayAnimationDuration: const Duration(milliseconds: 2000), autoPlay: true, enlargeCenterPage: true, height: 80),
items: data
.map(
(e) => Container(
margin: const EdgeInsets.only(top: 20.0, left: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(e["image"]),
fit: BoxFit.fitHeight,
),
// border:
// Border.all(color: Theme.of(context).accentColor),
borderRadius: BorderRadius.circular(32.0),
),
),
)
.toList());
}
}
}),
),
);
}
}

Related

How to display images from Frirebase Storage in StreamBuilder

I'm trying to display images from FirebaseStorage in StreamBuilder when user add them after they have been saved in FirebaseStorage
Try #1
It works but only the last added image is shown as stream and I would like to display all the images added.
I guess this try is the better way but I can't add ListView.builder because TaskSnapshot is one data and not a list of data like ListResult that's probably why I can't diplay all images and only the last one.
Widget:
Widget loadingImage(UploadTask uploadTask) => StreamBuilder<TaskSnapshot>(
stream: uploadTask.snapshotEvents,
builder: (context, snapshot) {
if(snapshot.hasData) {
final snap = snapshot.data;
final photoName = snap!.metadata!.name;
final photoType = snap.metadata!.contentType;
final photo = snapshot.data!.ref.getDownloadURL();
return StreamBuilder(
stream: photo.asStream(),
builder: (context, AsyncSnapshot<String> snapshot) {
final image = snapshot.data;
print("Image: $image");
return Row(
children: [
Image.network(
fit: BoxFit.cover,
width: 100,
height: 100,
image!,
),
const SizedBox(width: 20,),
Text(
photoName,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 20,),
Text(
photoType!,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
)
],
);
}
);
}
return Container();
},
);
Try #2
It displays images but not as stream if one is added it's not shown if a second one is added the first one will be displayed etc
DocumentViewModel:
//----------------------------------------------------------------------------
//----------------------------- Upload instructor document list --------------
//----------------------------------------------------------------------------
static Stream<ListResult>? uploadFileList(String uid) {
try {
final result = FirebaseStorage.instance
.ref("instructorDocuments/")
.child("$uid/")
.listAll();
return result.asStream();
} on FirebaseException catch (e) {
return null;
}
}
Widget:
Widget loadingImage(UploadTask uploadTask) => StreamBuilder<ListResult>(
stream: DocumentViewModel.uploadFileList(user!.uid),
builder: (context, snapshot) {
if(snapshot.hasData) {
final snap = snapshot.data;
return ListView.builder(
itemCount: snap!.items.length,
itemBuilder: (context, index) {
final photoName = snap.items[index].name;
final photoType = snap.items[index].getMetadata();
final photo = snap.items[index].getDownloadURL();
return StreamBuilder<FullMetadata>(
stream: photoType.asStream(),
builder: (context, AsyncSnapshot<FullMetadata> snapshot) {
if(snapshot.hasData) {
final type = snapshot.data!.contentType;
return StreamBuilder(
stream: photo.asStream(),
builder: (context, AsyncSnapshot<String> snapshot) {
if(snapshot.hasData) {
final image = snapshot.data;
return Row(
children: [
Image.network(
fit: BoxFit.cover,
width: 100,
height: 100,
image!,
),
const SizedBox(width: 20,),
Text(
photoName,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 20,),
Text(
type!,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
);
}
return Container();
},
);
}
return Container();
}
);
},
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
);
}
if(!snapshot.hasData) {
return const Loader();
}
if(snapshot.hasError) {
return Utils.showErrorMessage(snapshot.hasError.toString());
}
else {
return Container();
}
}
);
Thanks in advance
try this without streambuilder for getting images from firebase
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class BlogView extends StatefulWidget {
const BlogView({Key? key}) : super(key: key);
#override
State<BlogView> createState() => _BlogViewState();
}
var im;
var allimgList = [];
class _BlogViewState extends State<BlogView> {
#override
void initState() {
getData();
super.initState();
setState(() {
});
}
void getData() async {
allimgList=[];
await FirebaseFirestore.instance
.collection('Names')
.snapshots()
.forEach((event) {
var n=event.docs.length;
print(event.docs.length);
for (int i = 0; i <n; i++) {
im = event.docs[i]['Images'];
var nn=event.docs[i]['Images'].length;
for(int j=0;j<nn;j++){
allimgList.add(im[j]);
setState(() {});
}
if(i==n)break;
}
print("=========>" + allimgList.toString());
});
setState(() {
});
}
#override
Widget build(BuildContext context) {
// print("================lllllllll =>" + allimgList.toString());
return Scaffold(
appBar: AppBar(
title: Text("Blog"),
),
body: Container(
child: Center(
child: allimgList.length == 0 ?
Container(
height: 500,
width: 300,
child: Center(child: Text("No Image Added Yet")),
):Container(
margin: EdgeInsets.only(top: 10),
child: GridView.builder(
padding: EdgeInsets.only(left: 10, right: 10),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 150,
childAspectRatio: 4 / 4,
crossAxisSpacing: 10,
mainAxisSpacing: 20),
itemCount: allimgList.length,
itemBuilder: (BuildContext ctx, index) {
return Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15)),
child: Image.network(
allimgList[index],
fit: BoxFit.fill,
),
);
}),
),
),
),
);
}
}

Flutter Cubit fetching and displaying data

I'm trying to fetch data from Genshin API, code below is working, but only with delay (in GenshinCubit class), it looks weard, because I don't know how much time to set for delay. I think, there is a problem in code, cause it must not set the GenshinLoaded state before the loadedList is completed. Now, if I remove the delay, it just sets the GenshinLoaded when the list is still in work and not completed, await doesn't help. Because of that I get a white screen and need to hot reload for my list to display.
class Repository {
final String characters = 'https://api.genshin.dev/characters/';
Future<List<Character>> getCharactersList() async {
List<Character> charactersList = [];
List<String> links = [];
final response = await http.get(Uri.parse(characters));```
List<dynamic> json = jsonDecode(response.body);
json.forEach((element) {
links.add('$characters$element');
});
links.forEach((element) async {
final response2 = await http.get(Uri.parse(element));
dynamic json2 = jsonDecode(response2.body);
charactersList.add(Character.fromJson(json2));
});
return charactersList;
}
}
class GenshinCubit extends Cubit<GenshinState> {
final Repository repository;
GenshinCubit(this.repository) : super(GenshinInitial(),);
getCharacters() async {
try {
emit(GenshinLoading());
List<Character> list = await repository.getCharactersList();
await Future<void>.delayed(const Duration(milliseconds: 1000));
emit(GenshinLoaded(loadedList: list));
}catch (e) {
print(e);
emit(GenshinError());
}
}
}
class HomeScreen extends StatelessWidget {
final userRepository = Repository();
HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocProvider<GenshinCubit>(
create: (context) => GenshinCubit(userRepository)..getCharacters(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(body: Container(child: const CharactersScreen())),
),
);
}
}
class CharactersScreen extends StatefulWidget {
const CharactersScreen({
Key? key,
}) : super(key: key);
#override
State<CharactersScreen> createState() => _CharactersScreenState();
}
class _CharactersScreenState extends State<CharactersScreen> {
#override
Widget build(BuildContext context) {
return Column(
children: [
BlocBuilder<GenshinCubit, GenshinState>(
builder: (context, state) {
if (state is GenshinLoading) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is GenshinLoaded) {
return SafeArea(
top: false,
child: Column(
children: [
Container(
color: Colors.black,
height: MediaQuery.of(context).size.height,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: state.loadedList.length,
itemBuilder: ((context, index) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 50.0, horizontal: 50),
child: GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CharacterDetailsPage(
character: state.loadedList[index],
),
),
),
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.blueAccent.withOpacity(0.3),
borderRadius: const BorderRadius.all(
Radius.circular(
30,
),
)),
child: Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(
right: 30.0, bottom: 30),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
state.loadedList[index].name
.toString(),
style: TextStyle(
color: Colors.black,
fontSize: 50),
),
RatingBarIndicator(
itemPadding: EdgeInsets.zero,
rating: double.parse(
state.loadedList[index].rarity
.toString(),
),
itemCount: int.parse(
state.loadedList[index].rarity
.toString(),
),
itemBuilder: (context, index) =>
Icon(
Icons.star_rate_rounded,
color: Colors.amber,
))
],
),
),
),
),
),
);
})),
),
],
),
);
}
if (state is GenshinInitial) {
return Text('Start');
}
if (state is GenshinError) {
return Text('Error');
}
return Text('Meow');
}),
],
);
}
}
I found a solution!
I've got that problem because of forEach. How to wait for forEach to complete with asynchronous callbacks? - there is a solution.

How to create carousel slider with firestore image and onclick launch url in flutter?

I want to create carousel slider in flutter with cloud firestore. I created cloud firestore collection with the name of "slider" and i have two fields one is "image" and another one is "url".
Now i need to stream firestore collection in my carousel slider and when user click image, want to launch url.
My Carousel Slider Code
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
class Dashboard extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
SizedBox(height: 15.0),
CarouselSlider(
options: CarouselOptions(
height: 400.0,
enlargeCenterPage: true,
autoPlay: true,
aspectRatio: 16 / 9,
autoPlayCurve: Curves.fastOutSlowIn,
enableInfiniteScroll: true,
autoPlayAnimationDuration: Duration(milliseconds: 800),
viewportFraction: 0.8),
items: [
Container(
margin: EdgeInsets.all(5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
image: AssetImage('$show Firestore image'),
onPressed: () {
launchURL(
"$ launch firestore url");
}
fit: BoxFit.cover,
),
),
),
],
),
],
);
}
}
Can anyone guide me?
Widget build(BuildContext context) {
var idx = 1;
return Container(
margin: EdgeInsets.only(top: 4.0, bottom: 8.0),
height: getProportionateScreenHeight(150),
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xFF4A3298),
borderRadius: BorderRadius.circular(20),
),
child:StreamBuilder(
stream: FirebaseFirestore.instance.collection(BANNER_URL).snapshots(),
builder: (context, AsyncSnapshot snapshot) {
List list = []..length;
switch (snapshot.connectionState) {
case ConnectionState.none:
return Container(
child: Center(
child: new Text(
'No network. \nPlease, check the connection.')),
);
break;
case ConnectionState.waiting:
return Container(
child: Center(child: new CircularProgressIndicator()),
);
break;
default:
if (snapshot.hasError) {
return Container(
child: Center(
child: Text(snapshot.error.toString()),
),
);
} else if (snapshot.hasData) {
for (int i = 0; i < snapshot.data.size; i++) {
debugPrint("Index is " + idx.toString());
list.add(NetworkImage(
snapshot.data.docs[i].data()['image_url']));
idx++;
}
return ClipRect(
child: Banner(
message: "Publicite aqui",
location: BannerLocation.topEnd,
color: Colors.red,
child: Carousel(
boxFit: BoxFit.cover,
images: list,
autoplay: true,
animationCurve: Curves.fastLinearToSlowEaseIn,
animationDuration: Duration(milliseconds: 2000),
dotSize: 2.0,
dotColor: AppTheme.cuyuyuOrange400,
dotBgColor: AppTheme.cuyuyuTransparent,
indicatorBgPadding: 2.0,
)),
);
}
}
}),
);
}
You can make use of a FutureBuilder to fetch the document snapshot, and on completion, you can store the URLs in a list and use the list for the Carousel
Example code which uses FutureBuilder to fetch a list of urls:
Future getCarouselWidget() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection("carousel").getDocuments();
return qn.documents;
}
Widget build(BuildContext context) {
var idx = 1;
return Container(
child: FutureBuilder(
future: getCarouselWidget(),
builder: (context, AsyncSnapshot snapshot) {
List<NetworkImage> list = new List<NetworkImage>();
if (snapshot.connectionState == ConnectionState.waiting) {
return new CircularProgressIndicator();
} else {
if (snapshot.hasError) {
return new Text("fetch error");
} else {
//Create for loop and store the urls in the list
for(int i = 0; i < snapshot.data[0].data.length; i++ ) {
debugPrint("Index is " + idx.toString());
list.add(NetworkImage(snapshot.data[0].data["img_"+idx.toString()]));
idx++;
}
return new Container(
height: 250.0,
child: new Carousel(
boxFit: BoxFit.cover,
images: list, <== Set the list here
autoplay: true,
dotSize: 4.0,
indicatorBgPadding: 4.0,
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(milliseconds: 1000),
));
}
}
}),
);

display alert when data is changed using flutter?

My screen look like thisI have trying to display alert when snapshot.data value has been changed.i try the if else condition
import 'dart:async';
import 'dart:convert';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import'package:flutter_custom_clippers/flutter_custom_clippers.dart';
import 'package:tv_dashboard/pages/test.dart';
//import 'package:assets_audio_player/assets_audio_player.dart';
class DashBoard extends StatefulWidget {
#override
_DashBoardState createState() => _DashBoardState();
}
var now = new DateTime.now();
String g = ('${now.day}-${now.month}-${now.year}');
AnimationController _controller;
Animation<double> _animation;
class _DashBoardState extends State<DashBoard> with TickerProviderStateMixin {
Timer timer;
int counter = 0;
Test data = Test();
Future<List<dynamic>> fetchUsers() async {
String url = 'http://us.rdigs.com/jsonData.php';
var result = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
if (result.statusCode == 200) {
//print(result.body);
//playSound();
return json.decode(result.body);
} else {
// If the server not return a 200 OK ,
// then throw the exception.
throw Exception('Failed');
}
}
playSound() async {
AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();
audioPlayer.open(Audio('assets/Ring.mp3'));
}
String name(dynamic name) {
return name['name'];
}
String leads(dynamic leads) {
return leads['leads'];
}
#override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 5), (Timer t) => addValue());
}
void addValue() {
setState(() {
//playSound();
counter++;
});
}
void alertBox() async {
await fetchUsers();
Container(
padding: EdgeInsets.only(left: 300),
child: AlertDialog(
title: Text('Alert Data'),
),
); //Use the response in the dialog
}
var totalLeads = 0;
var countLead = 0;
var allLeads;
#override
Widget build(BuildContext context) {
alertBox();
//playSound();
return Scaffold(
// backgroundColor: Color.fromRGBO(198, 159, 169, 1),
body: Column(
children: [
ClipPath(
clipper: OvalBottomBorderClipper(),
child: Container(
padding: EdgeInsets.only(top: 5),
height: 70,
color: Colors.cyan[100],
child: Center(
child: Column(
children: [
Text(
"Total Leads",
style: new TextStyle(fontSize: 28.0, fontFamily: 'Michroma'),
),
Text(
totalLeads.toString(),
style: new TextStyle(
fontSize: 25.0,
),
)
],
)),
),
),
Expanded(
child: FutureBuilder<List<dynamic>>(
future: fetchUsers(),
builder: (context, snapshot) {
if (snapshot.hasData) {
//total leads
//alertBox();
totalLeads = snapshot.data
.map<int>((m) => int.parse(m["leads"]))
.reduce((a, b) => a + b);
return GridView.builder(
itemCount: snapshot.data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 6,
childAspectRatio:
MediaQuery.of(context).size.height / 350,
),
padding: EdgeInsets.all(8),
itemBuilder: (BuildContext context, int index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
bottomRight: Radius.circular(20)),
side: BorderSide(color: Colors.black)),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.only(top: 10),
child: Column(
children: [
Text(
name(snapshot.data[index]),
style: new TextStyle(
fontSize: 25.0,
),
),
Container(
padding: EdgeInsets.only(top: 12),
child: Text(
leads(snapshot.data[index])
.toString(),
style: new TextStyle(
fontSize: 26.0,
color: Colors.blue),
))
],
)),
],
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return Center(child: CircularProgressIndicator());
}
}))
],
));
}
}
totalLeads is count of my all int value
sum is temp variable
my problem is when data is changed in json string then display the alert box in flutter
When data changed in string, you can show AlertDialog widget:
Future<void> showErrorDialog() async {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: SingleChildScrollView(
child: Text(
'Error message',
),
),
actions: <Widget>[
TextButton(
child: Text('Ok'),
onPressed: () => Navigator.of(context).pop(),
),
],
);
},
);
}

flutter check if data exists in firestore

I've been trying to check if user selected data matches with my firestore data.
onPressed: () async{
await Navigator.of(context).push(MaterialPageRoute(builder: (context) => Checker (
from: fromSel,
to: toSel,
)));
},
and in the second page i used
StreamBuilder(
stream: Firestore.instance
.collection('Schedules')
.where('from', isEqualTo: from)
.where('to', isEqualTo: to)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index){
DocumentSnapshot power = snapshot.data.documents[index];
print(power['from']);
print(power['to']);
return Container(
height: 200,
width: MediaQuery.of(context).size.width,
child: Column(
children: [
Text(power['from']),
Text(power['to'])
],
),
);
}
);
}),
so the problem i'm getting is it's not displaying the value when i use .where('from', isEqualTo: from) but it works when i use .where('from', isEqualTo: 'Adama'). and also works with .where('from', isEqualTo: from) when i instantiate from value manually like String from = 'Adama'
can you please tell me what the problem is?
and below is my firestore structure
below is the whole code for the checker (renamed to search)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:demo/BookingPages/budget.dart';
import 'package:demo/Lists/trip.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Search extends StatefulWidget {
final from, to, seat, adult, child, infant;
final DateTime arrive, depart;
Search(
{Key key, this.from, this.to, this.seat, this.arrive, this.depart, this.adult, this.infant, this.child})
: super(key: key);
#override
_SearchState createState() => _SearchState(from: from, to: to, seat: seat, adult: adult, child: child, infant: infant, arrive: arrive, depart: depart);
}
class _SearchState extends State<Search> {
// Stream<QuerySnapshot> comparision;
var from, to, seat, adult, child, infant;
final DateTime arrive, depart;
_SearchState(
{Key key, this.from, this.to, this.seat, this.arrive, this.depart, this.adult, this.infant, this.child});
Stream<QuerySnapshot> comparision(BuildContext context) async* {
try{
yield* Firestore.instance
.collection('Schedules')
.where('from', isEqualTo: from.toString())
.where('to', isEqualTo: to.toString())
// .where('dates', arrayContains: widget.depart.day)
.snapshots();
}catch(e){
print(e);
}
}
// #override
// void initState() {
// // TODO: implement initState
// comparision = Firestore.instance
// .collection('Schedules')
// .where('from', isEqualTo: from)
// .where('to', isEqualTo: to)
// .snapshots();
//
// super.initState();
// }
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: Firestore.instance
.collection('Schedules')
.where('from', isEqualTo: from)
.where('to', isEqualTo: to)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index){
DocumentSnapshot power = snapshot.data.documents[index];
print(power['from']);
print(power['to']);
return Container(
height: 200,
width: MediaQuery.of(context).size.width,
child: Column(
children: [
Text(power['from']),
Text(power['to'])
],
),
);
}
);
}),
)
// Expanded(
// child: StreamBuilder<QuerySnapshot>(
// stream: comparision,
// builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>snapshot) {
// if (!snapshot.hasData)
// return Center(child: CircularProgressIndicator());
// return ListView.builder(
// itemCount: snapshot.data.documents.length,
// itemBuilder: (context, index){
// DocumentSnapshot power = snapshot.data.documents[index];
// print(power['from']);
// print(power['to']);
// return Container(
// height: 200,
// width: MediaQuery.of(context).size.width,
// child: Column(
// children: [
// Text(power['from']),
// Text(power['to'])
// ],
// ),
// );
// }
// );
// },
// ),
// ),
],
)
);
}
}
class TripCard extends StatefulWidget {
#override
_TripCardState createState() => _TripCardState();
}
class _TripCardState extends State<TripCard> {
#override
Widget build(BuildContext context) {
return Container();
}
}
below is my first page code which includes the values
import 'package:flutter/material.dart';
import 'search.dart';
class Other extends StatefulWidget {
#override
_OtherState createState() => _OtherState();
}
class _OtherState extends State<Other> {
var from = [
'Addis Ababa', 'Adama', 'Dire Dawa', 'Ali Sabieh', 'Djibouti'
];
var fromSel = 'Addis Ababa';
var to = [
'Addis Ababa', 'Adama', 'Dire Dawa', 'Ali Sabieh', 'Djibouti'
];
var toSel = 'Djibouti';
#override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Container(
//height: 203,
child: Column(
children: [
SizedBox(height: 15,),
Container(
//decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: MediaQuery.of(context).size.width/2-19,
height: 60,
padding: EdgeInsets.symmetric(horizontal: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('From', style: TextStyle(
fontSize: 18,
color: Colors.grey
),),
SizedBox(height: 0,),
Expanded(
child: DropdownButton<String>(
underline: Container(color: Colors.transparent),
items: from.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value, style: TextStyle(
fontSize: 18
),),
);
}).toList(),
isExpanded: true,
isDense: false,
elevation: 5,
hint: Text('From'),
value: fromSel,
onChanged: (String newValue){
setState(() {
this.fromSel = newValue;
});
}),
),
],
),
),
Container(height: 50, child: VerticalDivider(color: Colors.grey)),
Container(
width: MediaQuery.of(context).size.width/2-19,
height: 60,
padding: EdgeInsets.symmetric(horizontal: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('To', style: TextStyle(
fontSize: 18,
color: Colors.grey
),),
SizedBox(height: 0,),
Expanded(
child: DropdownButton<String>(
underline: Container(color: Colors.transparent),
items: to.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value, style: TextStyle(
fontSize: 18
),),
);
}).toList(),
isExpanded: true,
isDense: false,
elevation: 5,
hint: Text('to'),
value: toSel,
onChanged: (String newValue){
setState(() {
this.toSel = newValue;
});
}),
),
],
),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
child: MaterialButton(
onPressed: () async{
await Navigator.of(context).push(MaterialPageRoute(builder: (context) => Search (
from: fromSel,
to: toSel,
depart: _startDate,
arrive: _endDate,
seat: _options[_selectedIndex],
adult: adultSel.toString(),
child: childSel.toString(),
infant: infantSel.toString(),
)));
},
minWidth: MediaQuery
.of(context)
.size
.width - 80,
height: 45,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
color: Colors.lightGreen,
splashColor: Colors.green,
child: Text(
"Search",
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
)
],
),
),
),
);
}
}