Searchdelegates class using flutter firebase - flutter

I have a searchDelagate class...inside the class i want to diapaly some dat that comes from the collection"users"...Here actually my problem is i have two collection users and company ..i want to dispaly the data that match with the uid of another collection company..so i tried to call the function like this
class SearchPage extends SearchDelegate {
CollectionReference _firebaseFirestore =
FirebaseFirestore.instance.collection('users').where('pid',isEqualTo:widget.uid);
but when use "widget.uid"it become an error
i attach the full code below
class SearchPage extends SearchDelegate {
CollectionReference _firebaseFirestore =
FirebaseFirestore.instance.collection('users').where('pid',isEqualTo:widget.uid);
#override
List<Widget>? buildActions(BuildContext context) {
return <Widget>[
IconButton(
onPressed: () {
query = "";
},
icon: Icon(Icons.close)),
];
}
#override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(Icons.arrow_back));
}
#override
Widget buildResults(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 500,
// color: Colors.indigo,
// height: 300,
child: Column(
children: [
Row(
children: [
buildTextTitle("Reg no", 60),
buildTextTitle("Name", 100),
buildTextTitle("Address", 100),
buildTextTitle("Phone", 100),
buildTextTitle("Monthly amount", 70),
buildTextTitle("Opening balance", 70),
],
),
const Divider(
height: 20,
thickness: 1,
color: Colors.black,
),
Expanded(
child: Container(
child: StreamBuilder<QuerySnapshot>(
stream: _firebaseFirestore.snapshots().asBroadcastStream(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else {
print(snapshot.data);
return ListView(
children: [
...snapshot.data!.docs
.where(
(QueryDocumentSnapshot<Object?> element) =>
element["RegNo"]
.toLowerCase()
.contains(query.toLowerCase()))
.map((QueryDocumentSnapshot<Object?> data) {
final String regno = data.get("RegNo");
final String name = data["Name"];
final String phone = data["Phone"];
final String address = data["Address"];
final String opening = data["Opening"];
final String monthly = data["Monthly"];
final String id = data["id"];
final String pid = data["pid"];
final String pdis = data["pdis"];
final String pemail = data["pemail"];
final String pname = data["pname"];
final String pphone = data["pphone"];
final String pregno = data["pregno"];
final String ppost = data["ppost"];
//final String id=data["id"];
return Container(
// height:100,
//width: 150,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
CollectionPage(
RegNo: regno,
Phone: phone,
Name: name,
Address: address,
Monthly: monthly,
Opening: opening,
id: id,
pdis: pdis,
pemail: pemail,
pid: pid,
pname: pname,
pphone: pphone,
ppost: ppost,
pregno: pregno,
)));
},
child: Column(
children: [
Row(
children: [
buildSizedBox(regno, 60),
buildSizedBox(name, 100),
buildSizedBox(address, 100),
buildSizedBox(phone, 100),
buildSizedBox("${monthly}/-", 70),
buildSizedBox("${opening}/-", 70),
],
),
Row(
children: [
Expanded(
child: const Divider(
height: 20,
thickness: 1,
// indent: 200,
// endIndent: 50,
color: Colors.green,
),
)
],
),
],
),
),
);
})
],
);
}
},
),
),
),
],
),
),
),
);
}
#override
Widget buildSuggestions(BuildContext context) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 500,
child: Column(
children: [
Row(
children: [
buildTextTitle("Reg no", 60),
buildTextTitle("Name", 100),
buildTextTitle("Address", 100),
buildTextTitle("Phone", 100),
buildTextTitle("Monthly amount", 70),
buildTextTitle("Opening balance", 70),
],
),
const Divider(
height: 20,
thickness: 1,
color: Colors.black,
),
Expanded(
child: SingleChildScrollView(
child: Container(
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('users')
where('pid',isEqualTo: widget.uid)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return CircularProgressIndicator();
{
return ListView.separated(
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
physics: const NeverScrollableScrollPhysics(),
separatorBuilder: (context, index) {
return Container();
},
itemBuilder: (BuildContext context, int index) {
return Container(
// height:100,
//width: 150,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
CollectionPage(
RegNo: snapshot.data
?.docs[index]['RegNo'],
Phone: snapshot.data
?.docs[index]['Phone'],
Name: snapshot.data
?.docs[index]['Name'],
Address: snapshot.data
?.docs[index]['Address'],
Monthly: snapshot.data
?.docs[index]['Monthly'],
Opening: snapshot.data
?.docs[index]['Opening'],
id: snapshot.data?.docs[index]
['id'],
pdis: snapshot.data
?.docs[index]['pdis'],
pemail: snapshot.data
?.docs[index]['pemail'],
pid: snapshot
.data?.docs[index]['pid'],
pname: snapshot.data
?.docs[index]['pname'],
pphone: snapshot.data
?.docs[index]['pphone'],
ppost: snapshot.data
?.docs[index]['ppost'],
pregno: snapshot.data
?.docs[index]['pregno'],
)));
},
child: Column(
children: [
Row(
children: [
buildSizedBox(
snapshot.data!.docs[index]
['RegNo'],
60),
buildSizedBox(
snapshot.data!.docs[index]
['Name'],
100),
buildSizedBox(
snapshot.data!.docs[index]
['Address'],
100),
buildSizedBox(
snapshot.data!.docs[index]
['Phone'],
100),
buildSizedBox(
"${snapshot.data!.docs[index]['Monthly']}/-",
70),
buildSizedBox(
"${snapshot.data!.docs[index]['Opening']}/-",
70),
],
),
Row(
children: [
Expanded(
child: const Divider(
height: 20,
thickness: 1,
// indent: 200,
// endIndent: 50,
color: Colors.green,
),
)
],
),
],
),
),
);
},
);
}
},
),
),
),
),
],
),
),
),
);
}
SizedBox buildSizedBox(String value, double size) {
return SizedBox(
width: size,
child: Text(
value,
style: const TextStyle(
letterSpacing: 0,
color: Colors.black,
fontSize: 15,
fontWeight: FontWeight.w400),
));
}
SizedBox buildTextTitle(String title, double width) {
return SizedBox(
width: width,
child: Text(
title,
style: const TextStyle(
letterSpacing: 0,
color: Colors.red,
fontSize: 14,
fontWeight: FontWeight.w500),
),
);
}
}

Related

VideoPlayer working locally but is only playing audio in production

Im using the videoPlayer package and it has been working perfectly until i decided to change the format of the video to take height: MediaQuery.of(context).size.height and now it suddenly only plays the audio in production while working perfectly on my local device.
I have posten the full code below along with an image displaying what the error looks like enter image description here
class InspoDescription extends StatefulWidget {
String id;
String title;
String image;
String name;
String tag;
String description;
String video;
InspoDescription(
{required this.id,
required this.title,
required this.image,
required this.name,
required this.tag,
required this.description,
required this.video});
#override
State<InspoDescription> createState() => _InspoDescriptionState();
}
class _InspoDescriptionState extends State<InspoDescription> {
VideoPlayerController? controller;
#override
void initState() {
controller = VideoPlayerController.network(widget.video)
..addListener(() => setState(() {}))
..setLooping(true)
..initialize().then((value) => controller!.play());
super.initState();
}
#override
void dispose() {
controller!.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
),
body: SingleChildScrollView(
child: Column(
children: [
controller!.value.isBuffering
? SizedBox(
width: double.infinity,
height: MediaQuery.of(context).size.height,
child: const Center(
child: CircularProgressIndicator(),
),
)
: Positioned.fill(
child: GestureDetector(
onTap: () => controller!.value.isPlaying
? controller!.pause()
: controller!.play(),
child: SizedBox(
width: double.infinity,
height: MediaQuery.of(context).size.height,
child: Stack(
children: [
VideoPlayer(controller!),
controller!.value.isPlaying
? Container()
: const Align(
alignment: Alignment.center,
child: Icon(
Icons.play_arrow_rounded,
size: 100,
color: Color.fromRGBO(255, 255, 255, 0.6),
),
),
const Align(
alignment: Alignment.bottomCenter,
child: Icon(
Icons.arrow_drop_down_sharp,
size: 100,
color: Color.fromRGBO(255, 255, 255, 0.6),
),
)
],
),
),
),
),
ExploreHeadline(
name: widget.name,
tag: widget.tag,
title: widget.title,
description: widget.description,
),
StreamBuilder<InspoModel>(
stream: Inspo().getCurrentExplorePage(widget.id),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong ${snapshot.error}');
} else if (snapshot.hasData) {
final inspo = snapshot.data;
List<ProductModel> products = [];
inspo!.products.forEach(
(element) {
ProductModel product = ProductModel.fromJson(element);
products.add(product);
},
);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GridView.builder(
itemCount: products.length,
shrinkWrap: true,
itemBuilder: (context, index) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: GestureDetector(
onTap: () => Navigator.of(context).push(
CustomPageRoute(
child: ProductDescription(
sub_cat_id: products[index].id,
productId: products[index].id,
description: products[index]
.description,
details: products[index].details,
productImage: products[index].image,
productName: products[index].title,
productPrice: products[index].price,
cartQuantity:
products[index].cartQuantity,
categoryId:
products[index].category_id,
subTitle: products[index].subTitle,
inventory:
products[index].inventory))),
child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(16),
),
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: CachedNetworkImage(
imageUrl: products[index].image,
),
),
],
),
),
),
),
Text(
products[index].title,
style: TextStyle(
color: Colors.grey[500],
fontWeight: FontWeight.w400),
),
Text(
products[index].subTitle,
),
Text(
'${products[index].price} kr',
)
],
),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.75,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
),
),
);
} else {
return const CircularProgressIndicator();
}
}),
],
),
),
);
}
}
Video on local device
Full page on local device

passing data from homepage to detail page with firestore flutter

I want to display a group of books on the main page (this is working fine!), but right now I want to navigate to a dynamic detail page if I click on the book, but I don't know how to do it properly. Can anyone explain how to navigate to a detail page with firestore data ?
models
class Buecher {
String autor;
String buchtitel;
String bild;
int id;
Buecher({
required this.autor,
required this.id,
required this.buchtitel,
required this.bild,
});
}
getting data from firestore
Buecher _bouksListFromSnapshot(DocumentSnapshot snapshot) {
return Buecher(
autor: snapshot.get('author') ?? '',
buchtitel: snapshot.get('buchtitel') ?? '',
bild: snapshot.get('bild') ?? '',
id: snapshot.get('id') ?? '0',
);
}
Stream<Buecher> get bouks {
return brewCollection.doc().snapshots()
.map(_bouksListFromSnapshot);
}
}
main page
class BrewList extends StatefulWidget {
#override
_BrewListState createState() => _BrewListState();
}
class _BrewListState extends State<BrewList> {
#override
Widget build(BuildContext context) {
final buecher = Provider.of<List<Buecher>>(context);
//print(brews.documents);
return SizedBox(
height: 50,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: buecher.length,
itemBuilder: (context, index) {
return BrewTile(
buecher: buecher[index],
);
},
),
);
}
}
class BrewTile extends StatelessWidget {
final Buecher buecher;
BrewTile({required this.buecher});
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Row(children: [
InkWell(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: AppColors.backColor,
elevation: 0.0,
shadowColor: Colors.transparent,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailForm(buech:buecher),
));
},
child: Container(
margin: EdgeInsets.fromLTRB(10, 0, 0, 5),
height: 320,
width: 170,
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.asset(
"${buecher.bild}",
width: 170.0,
height: 230.0,
fit: BoxFit.cover,
),
),
Expanded(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
BigText(
height: 1.5,
text: buecher.buchtitel,
size: 17,
color: AppColors.mainColor,
),
SmallText(
text: buecher.autor,
size: 16,
color: AppColors.FontColor,
),
],
)),
),
],
),
),
),
),
]));
}
}
detail page
class DetailForm extends StatelessWidget {
Buecher buech;
DetailForm({
Key? key, required this.buech
}) : super(key: key);
#override
Widget build(BuildContext context) {
return StreamBuilder<Buecher>(
stream: DatabaseService().bouks,
builder: (context, snapshot) {
if (snapshot.hasData) {
Buecher? buecherData = snapshot.data;
return MaterialApp(
home: Scaffold(
backgroundColor: AppColors.backColor,
appBar: AppBar(
backgroundColor: AppColors.backColor,
elevation: 0,
centerTitle: true,
leading: IconButton(
icon: Icon(FeatherIcons.chevronLeft),
color: AppColors.mainColor,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Profil()),
);
},
),
leadingWidth: 50,
title: BigText(
text: '${buecherData!.autor}',
),
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 340,
child: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
BuchContainer(
bild: "assets/image/GG.jpeg",
height: 260,
width: 200),
BigText(
text: '${buech.autor}',
color: AppColors.FontColor),
],
),
),
),
Container(
height: 70,
width: 360,
decoration: BoxDecoration(
color: AppColors.backColor2,
borderRadius: BorderRadius.circular(25.0)),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Icon(Icons.star),
BigText(text: '4.8'),
SmallText(
text: '/5', color: AppColors.FontColor),
SmallText(
text: '|',
color: AppColors.FontColor,
size: 20),
BigText(text: '4.2k'),
SmallText(
text: 'Read', color: AppColors.FontColor),
SmallText(
text: '|',
color: AppColors.FontColor,
size: 20),
BigText(text: '120'),
SmallText(
text: 'pages',
color: AppColors.FontColor),
],
)),
Container(
margin: EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10),
BigText(text: 'Synopsis'),
SizedBox(height: 20),
Text(
'The story of the mysteriously wealthy Jay Gatsby and his love for the beautiful Daisy Buchanan, of lavish parties on Long Island at a time when The New York Times noted “gin was the national drink and sex the national obsession,” it is an exquisitely crafted tale of America in the 1920s.',
style: TextStyle(
height: 1.5,
fontSize: 16,
),
)
],
)),
],
),
)));
} else {
return Text('error');
}
});
}
}

The method was called on null Flutter error

I have seen many people having this error in other StackOverflow posts but when I am struggling to implement the answers to other questions to my own code. The code being used is from the GitHub repository https://github.com/sbis04/events_demo.
This is how I call the method:
class _ThirdRoute extends State<ThirdRoute> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Calendar"),
),
body: Column(
children: <Widget>[
DashboardScreen(),
],
),
);
}
}
And this is the method in another .dart file:
class DashboardScreen extends StatefulWidget {
#override
_DashboardScreenState createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
Storage storage = Storage();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: Colors.grey, //change your color here
),
title: Text(
'Event Details',
style: TextStyle(
fontSize: 22,
),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CreateScreen(),
),
);
},
),
body: Padding(
padding: const EdgeInsets.only(
left: 16.0,
right: 16.0,
),
child: Container(
child: StreamBuilder(
stream: storage.retrieveEvents(),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data.documents.length > 0) {
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
Map<String, dynamic> eventInfo = snapshot.data.documents[index].data();
EventInfo event = EventInfo.fromMap(eventInfo);
DateTime startTime = DateTime.fromMillisecondsSinceEpoch(event.startTimeInEpoch);
DateTime endTime = DateTime.fromMillisecondsSinceEpoch(event.endTimeInEpoch);
String startTimeString = DateFormat.jm().format(startTime);
String endTimeString = DateFormat.jm().format(endTime);
String dateString = DateFormat.yMMMMd().format(startTime);
return Padding(
padding: EdgeInsets.only(bottom: 16.0),
child: InkWell(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => EditScreen(event: event),
),
);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: EdgeInsets.only(
bottom: 16.0,
top: 16.0,
left: 16.0,
right: 16.0,
),
= child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10),
Text(
event.description,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Text(
event.link,
),
),
SizedBox(height: 10),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 50,
width: 5,
),
SizedBox(width: 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
dateString,
),
Text(
'$startTimeString - $endTimeString',
),
],
)
],
),
],
),
),
],
),
),
);
},
);
} else {
return Center(
child: Text(
'No Events',
),
);
}
}
return Center(
child: CircularProgressIndicator(
strokeWidth: 2,
),
);
},
),
),
),
);
}
}
If anyone would be able to give me some advice on how to solve the error:
The method 'collection' was called on null. Receiver: null. Tried calling: collection("events"). The relevant error-causing widget was DashboardScreen
EDIT This is my storage.dart file as requested in the comments:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'calendar_client.dart';
final CollectionReference mainCollection = FirebaseFirestore.instance.collection('event');
final DocumentReference documentReference = mainCollection.doc('test');
class Storage {
Future<void> storeEventData(EventInfo eventInfo) async {
DocumentReference documentReferencer = documentReference.collection('events').doc(eventInfo.id);
Map<String, dynamic> data = eventInfo.toJson();
print('DATA:\n$data');
await documentReferencer.set(data).whenComplete(() {
print("Event added to the database, id: {${eventInfo.id}}");
}).catchError((e) => print(e));
}
Future<void> updateEventData(EventInfo eventInfo) async {
DocumentReference documentReferencer = documentReference.collection('events').doc(eventInfo.id);
Map<String, dynamic> data = eventInfo.toJson();
print('DATA:\n$data');
await documentReferencer.update(data).whenComplete(() {
print("Event updated in the database, id: {${eventInfo.id}}");
}).catchError((e) => print(e));
}
Future<void> deleteEvent({#required String id}) async {
DocumentReference documentReferencer = documentReference.collection('events').doc(id);
await documentReferencer.delete().catchError((e) => print(e));
print('Event deleted, id: $id');
}
Stream<QuerySnapshot> retrieveEvents() {
Stream<QuerySnapshot> myClasses = documentReference.collection('events').orderBy('start').snapshots();
return myClasses;
}
}

How to sent data into two different class within a file using navigator in flutter

I am lost my direction. Can Someone help me how can I send my data from the first page to the second page using Navigator? There are two types of class that exist in the destination file which are a stateful widget and a stateless widget. I am trying to send data from the first page using navigator:
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW(category :categoriesList[index].name)));
The restaurantLISTVIEW is a stateful class on the second page. How can I share the data with the stateless class within the same file?
My full code on the first page:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:phpfood/restaurantlist.dart';
//import 'globals.dart' as globals;
import 'custom_textW.dart';
class Category {
final String name;
final String image;
Category({#required this.name, #required this.image});
}
List<Category> categoriesList = [
Category(name: "Breakfast", image: "nasilemak.png"),
//Category(name: "Kuih", image: "kuih.png"),
Category(name: "Lunch", image: "lunch.png"),
//Category(name: "Minum Petang", image: "mnmptg.png"),
Category(name: "Dinner", image: "mknmlm.png"),
//Category(name: "Minum Malam", image: "mnmmlm.png"),
//Category(name: "Minuman", image: "air.png"),
];
class Categories extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 120,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categoriesList.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.only(left: 28.0, top: 8),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(
color: Colors.red[200], offset: Offset(4, 6), blurRadius: 20)
]),
//tambah di sini kalau nk gesture
child: InkWell(
//onTap: ()=> Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(),)),
onTap: (){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW(category :categoriesList[index].name)));
},
/*{
if(categoriesList[index].name == "Breakfast"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW(category: 'breakfast')));
//Navigator.of(context).push(MaterialPageRoute<void>(builder: (context) => restaurantLISTVIEW(category: 'breakfast',),),);
}
else if(categoriesList[index].name == "Lunch"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW()));
}
else if(categoriesList[index].name == "Dinner"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW()));
}
},*/
child: Image.asset(
"images/${categoriesList[index].image}",
width: 100,
),
),
),
SizedBox(
height: 5,
),
CustomText(
text: categoriesList[index].name,
size: 17,
colors: Colors.black,
)
],
),
);
},
),
);
}
}
My full code on the second page:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'breakfast.dart';
// ignore: camel_case_types
class restaurantLISTVIEW extends StatefulWidget {
restaurantLISTVIEW({this.category});
final String category;
#override
_restaurantLISTVIEWState createState() => _restaurantLISTVIEWState();
}
// ignore: camel_case_types
class _restaurantLISTVIEWState extends State<restaurantLISTVIEW> {
Future<List> getData() async{
var url = 'http://10.0.2.2/foodsystem/restaurantlist.php';
var data = {'product_type': 'xde pape ppon saje nk hantar value'};
var response = await http.post(url, body: json.encode(data));
//final response= await http.get("http://10.0.2.2/foodsystem/getdata.php");
return json.decode(response.body);}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
//Text("Restaurant's Owner Page"),
Text('${widget.category}', textAlign: TextAlign.center, style: TextStyle(fontSize: 25, fontWeight: FontWeight.w700), ),
],
),
centerTitle: false,
//automaticallyImplyLeading: false,
),
body:
Padding(
padding: const EdgeInsets.only(bottom: 20, left: 5, right: 5),
child: Column(
children: [
SizedBox(height: 30,),
Container(
//decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(15)),
height: 600,
child: FutureBuilder<List>(
future: getData(),
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData ?
ItemList(list: snapshot.data,) :
Center(child: CircularProgressIndicator(),);
},
),
),
FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
'${widget.category}'
),
);
},
);
},
),
SizedBox(height: 10,),
],
),
),
);
}
}
class ItemList extends StatelessWidget {
final List list;
final String category;
ItemList({this.list, this.category});
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
//color: Colors.red.shade100,
height: 600,
child: ListView.builder(
itemCount: list==null ? 0 : list.length,
itemBuilder: (context, i){
return new Container(
height: 200,
child: new GestureDetector(
onTap: ()
{Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(list: list, index: i, category: category,)));},
/*{
if(category == "Breakfast"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(list: list, index: i, category: category,)));
}
},*/
child: new Card(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
'$category hellp'
),
);
},
);
},
),
Row(
children: [
Container(
constraints: BoxConstraints(minWidth: 180, maxWidth: 180),
child:
Column(
children: [
Text(list[i]["restaurant_name"], style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), textAlign: TextAlign.center,),
Text("Restaurant ID: ${list[i]["restaurant_id"]}", style: TextStyle(fontSize: 20,), textAlign: TextAlign.center,),
],
),
),
Padding(
padding: const EdgeInsets.only(left :20.0),
child: Container(
constraints: BoxConstraints(minWidth: 150, maxWidth: 300),
child:
SizedBox(
width: 50,
child: Column(
children: [
Text("SSM: ${list[i]["restaurant_ssm"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 15),),
Text("Phone: ${list[i]["restaurant_phone"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 15),),
Text("Address: ${list[i]["restaurant_address"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 15),),
],
),
),
),
),
],
),
Row(
children: [
],
),
],
),
),
),
);
},
),
),
);
}
}
As you can see in the stateless class, I am already calling the value from the first page, but it returns null because there is nothing forwarded to that class.
The problem is that you did not share the name data for the ItemList class through the category parameter:
make the following correction:
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData ?
ItemList(list: snapshot.data, category: widget.category) :
Center(child: CircularProgressIndicator(),);
},
a tip is to use the #required notation in the widget constructor so as not to forget to fill in the named parameters. Example:
class ItemList extends StatelessWidget {
final List list;
final String category;
ItemList({#required this.list, #required this.category});
#override
Widget build(BuildContext context) {
return Container();
}
}

Flutter Firebase: not able update Database

I want to update my Collection with an NumberPicker in a Alert Dialog. I do not get any errors in code or from the emulator. When i press the button to update the code the terminal do not give any errors. Everything looks fine but for some reason i do not work. When you need more Information just leave a comment with what you excactly need. :)
import 'package:flutter/material.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:testapp/services/Services.dart';
import 'models/Goals.dart';
class Statistics extends StatefulWidget {
#override
_StatisticsState createState() => _StatisticsState();
}
class _StatisticsState extends State<Statistics> {
int _currentFirstValue = 1;
int totalFirst;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 260,
child: StreamBuilder(
stream: FirestoreService().getGoals(),
builder: (context, AsyncSnapshot<List<Goal>> snapshot) {
if (snapshot.hasError || !snapshot.hasData) {
return Center(child: CircularProgressIndicator(
backgroundColor: Color(0XFF1954A1),
));
}
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
// ignore: missing_return
Goal goal = snapshot.data[index];
return Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
height: 230,
width: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey[300],
offset: const Offset(0.5, 1),
blurRadius: 4.0,
spreadRadius: 0.1,
),
]),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text('WeekGoals', style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),),
SizedBox(width: 100),
SizedBox(
height: 20,
width: 87,
child: FlatButton(
child: Text('edit', style: TextStyle(
fontSize: 17,
color: Colors.yellow[700]
),),
onPressed: () {
return showDialog(
context: context,
barrierDismissible: true,
builder: (context) => AlertDialog(
content: Column(
children: <Widget>[
Text('weekly goals'),
NumberPicker.integer(
initialValue: _currentFirstValue,
minValue: 1,
maxValue: 100,
onChanged: (newGoal) => setState(() => {
_currentFirstValue = newGoal,
totalFirst = _currentFirstValue,
})
),
Row(
children: <Widget>[
RaisedButton(
child: Text('edit goals'),
onPressed: () async {
Goal goal = Goal(
weekActivityGoal: totalFirst,
);
await FirestoreService().updateGoal(goal);
Navigator.pop(context, false);
},
),
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.pop(context, false);
},
)
],
)
],
),
)
);
},
),
)
],
),
SizedBox(height: 10),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 17.5),
child: CircularPercentIndicator(
header: Text('activitys', style: TextStyle(
fontSize: 17,
),),
radius: 130,
progressColor: Colors.red,
lineWidth: 8,
backgroundColor: Colors.grey[200],
percent: goal.weekActivity*100/goal.weekActivityGoal,
center: Text('${goal.weekActivity}/${goal.weekActivityGoal}'),
),
),
],
),
],
),
),
],
);
});
}),
),
);
}
}
Here this has been helping a lot of people try i out might help you too.
StreamBuilder(
stream: Firestore.instance.collection('Hearings').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Select lot');
case ConnectionState.waiting:
return Text('Awaiting bids...');
case ConnectionState.active:
{
print('active');
return Text('${snapshot.data}');
}
case ConnectionState.done:
{
print('Done');
return _buildList(context, snapshot.data);
}
}
return null;
}),
));
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => Firestore.instance.runTransaction((transaction) async {
final freshSnapshot = await transaction.get(record.reference);
final fresh = Record.fromSnapshot(freshSnapshot);
await transaction
.update(record.reference, {'votes': fresh.votes + 1});
}),
),
),
);
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
This is where the link this info came from.