How to sent data into two different class within a file using navigator in flutter - 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();
}
}

Related

WebViewController. Exception has occurred. ArgumentError (Invalid argument(s): Missing scheme in uri: null)

I am trying to pass data from previous page(news_card.dart) to another page(news_details.dart) to view in WebViewController. but for loadRequest(Uri.parse(widget.link)) I have received an error "Exception has occurred.
ArgumentError (Invalid argument(s): Missing scheme in uri: null)"
Here is my code for news_card.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:lumi_news/page/news/news_details.dart';
class NewsCard extends StatelessWidget {
final CollectionReference collectionReference;
NewsCard({super.key, required this.collectionReference});
PageController? _controller;
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<QuerySnapshot>(
stream: collectionReference.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text("error");
}
if (snapshot.hasData) {
QuerySnapshot querySnapshot = snapshot.data;
List<QueryDocumentSnapshot> documents = querySnapshot.docs;
List<Map> items = documents
.map((e) => {
'id': e.id,
'newsTitle': e['newsTitle'],
'publisherName': e['publisherName'],
'imageUrl': e['imageUrl'],
'publisherImageUrl': e['publisherImageUrl'],
'publisherRectangleUrl': e['publisherRectangleUrl'],
'updated': e['updated'],
'link"': e['link'],
})
.toList();
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
Map thisItem = items[index];
return Container(
//padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
height: 150,
width: double.maxFinite,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewsDetails(
link: '${thisItem['link']}',
image: '${thisItem['publisherImageUrl']}',
title: '${thisItem['publisherName']}',
)));
},
child: Card(
elevation: 3,
child: Row(
children: <Widget>[
Container(
width: 110,
margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage('${thisItem['imageUrl']}'),
),
),
),
Container(
child: Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 10,
),
Text(
'${thisItem['publisherName']}',
style: TextStyle(
color: Colors.grey,
fontSize: 12,
),
),
Text(
'${thisItem['newsTitle']}',
maxLines: 3,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
SizedBox(
height: 30,
),
Text(
'${thisItem['updated']}',
style: TextStyle(
color: Colors.grey,
fontSize: 12,
),
),
],
),
),
),
],
),
),
),
);
},
);
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}
and here news_detail.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:webview_flutter/webview_flutter.dart';
class NewsDetails extends StatefulWidget {
final String link;
final String title;
final String image;
NewsDetails({required this.link, required this.title, required this.image});
#override
State<NewsDetails> createState() => _NewsDetailsState(link, title, image);
}
class _NewsDetailsState extends State<NewsDetails> {
WebViewController? _controller;
final String link;
final String title;
final String image;
_NewsDetailsState(this.link, this.image, this.title);
#override
void initState() {
// TODO: implement initState
super.initState();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// Update loading bar.
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(widget.link));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 1,
backgroundColor: Colors.white,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(
Icons.arrow_back,
color: Colors.black,
),
),
title: Container(
width: double.maxFinite,
child: Row(
children: <Widget>[
Container(
child: Image.network(
widget.image,
fit: BoxFit.contain,
height: 32,
),
),
Container(
padding: EdgeInsets.only(left: 5),
child: Text(
widget.title,
style: TextStyle(color: Colors.black),
),
)
],
),
),
),
body: WebViewWidget(controller: _controller!),
);
}
}
Does anyone know how to solve this? Thanks for any help !

List screen to product details scree

I'm confused in this. I have created a screen in with list to products data is coming from an dummy API. no I have created the cards and I want to display product details in next screen. how can I show the same product details on second screen of pressed product.
I think we need to store index of api data in a variable somehow. this is the code
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_get_api/model.dart';
import 'package:flutter_get_api/product_detail.dart';
import 'package:http/http.dart' as http;
class Details extends StatefulWidget {
Details({Key? key}) : super(key: key);
#override
State<Details> createState() => _DetailsState();
}
class _DetailsState extends State<Details> {
Future<Model> getProductsApi() async {
final responce =
await http.get(Uri.parse('https://dummyjson.com/products'));
var data = jsonDecode(responce.body.toString());
if (responce.statusCode == 200) {
return Model.fromJson(data);
} else {
return Model.fromJson(data);
}
}
var s = '\$';
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 32, 28, 80),
title: Text('Api Get'),
),
backgroundColor: Color.fromARGB(255, 32, 28, 80),
body: Column(
children: [
Expanded(
child: FutureBuilder<Model>(
future: getProductsApi(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.products!.length,
itemBuilder: (context, index) {
print(
snapshot.data!.products!.length,
);
return Column(
children: [
Padding(
padding: const EdgeInsets.all(5.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetails(),
));
},
child: Container(
height: 100,
width: 500,
child: Card(
color: Color.fromARGB(255, 185, 239, 243),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
10, 25, 10, 10),
child: CircleAvatar(
backgroundImage: NetworkImage(snapshot
.data!.products![index].thumbnail!
.toString()),
),
),
Flexible(
child: Padding(
padding: const EdgeInsets.fromLTRB(
8, 10, 8, 0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Text(
snapshot
.data!.products![index].title
.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17),
),
Text(
snapshot
.data!.products![index].brand
.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
Text(
snapshot.data!.products![index]
.description
.toString(),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('\$' +
snapshot.data!.products![index].price
.toString()),
),
],
),
),
),
),
Pass your selected product to the ProductDetails constructor
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetails(snapshot.data!.products[index]),));
Watch the basics here: https://docs.flutter.dev/cookbook/navigation/passing-data
You can pass through constructor
class ProductDetails extends StatefulWidget {// can be StatelessWidget
final data; // better use DataType like `final ModeClass data
const ProductDetails({super.key, required this.data});
Now you can pass it like
builder: (context) => ProductDetails(snapshot.data!.products![index]),
Also you can pass with route arguments. Check more about navigation/passing-data

flutter putting data from api in expansion tile

Hew guys , i got a small question .
im making a drawer that should have a titles and a neste titles so i use an expansion tile.
so the titles are displayed but when i press the arrow to open the nested titles it gives me an error.
i used future builder in the nested titles i think this is the problem the error gives me this
The following TypeErrorImpl was thrown building FutureBuilder<List<dynamic>>(dirty, state: _FutureBuilderState<List<dynamic>>#aeb31):
Unexpected null value.
this is my drawer
Drawer Image
this is my drawer code
import 'package:MyCima/Screens/drawer_title_page.dart';
import 'package:MyCima/models/drawer_shows_data_model.dart';
import 'package:MyCima/services/services.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants.dart';
class FilmsDrawer extends StatefulWidget {
const FilmsDrawer({Key? key}) : super(key: key);
#override
_FilmsDrawerState createState() => _FilmsDrawerState();
}
class _FilmsDrawerState extends State<FilmsDrawer> {
final ServicesClass _services = ServicesClass();
late DrawerShowsDataModel _showsModelClass;
late Future drawerListData;
List nestedListNames = [];
#override
void initState() {
drawerListData = getDrawerList();
super.initState();
}
Future<List> getDrawerList() async {
return await _services.getFilms('menus');
}
#override
Widget build(BuildContext context) {
return Drawer(
elevation: 150,
semanticLabel: 'More Shows',
backgroundColor: PRIMARY,
child: Padding(
padding: const EdgeInsets.only(top: 24),
child: FutureBuilder(
future: drawerListData,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
return const Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
return Column(
children: [
Expanded(
flex: 5,
child: Column(
children: [
Expanded(
flex: 9,
child: Text(
'MyCima',
style: GoogleFonts.bevan(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const Expanded(
flex: 1,
child: Divider(
color: Colors.white,
indent: 64,
endIndent: 64,
),
),
],
),
),
Expanded(
flex: 95,
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
_showsModelClass = DrawerShowsDataModel.fromJson(
snapshot.data[index]);
if (_showsModelClass.listChildren.length > 0) {
return ExpansionTile(
title: Text(
_showsModelClass.name,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
children: [
getNestedTitles(index),
],
);
} else {
return Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.all(8),
child: TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DrawerTitlePage()));
},
child: Text(
'${_showsModelClass.name}',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
);
}
}),
),
],
);
case ConnectionState.none:
return const Center(child: Text('No Connection'));
}
},
),
),
);
}
getNestedTitles(int index){
return FutureBuilder(
future: getDrawerList(),
builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
return ListView.builder(
itemCount: snapshot.data![index]['children'].length,
itemBuilder: (BuildContext context, int index) {
_showsModelClass = DrawerShowsDataModel.fromNestedJson(snapshot.data![index]['children'][index]);
return TextButton(
onPressed: () {},
child: Text(
'${_showsModelClass.name}',
),
);
},
);
},
);
}
}
i found the answer
we need to make a list of widgets and add widgets on it then use it in the expansion
List<Widget> list = [];
List<Widget> getNestedTitles(int index) {
List<Widget> list = [];
drawerListData.then((value) {
for (var x in value[index]['children']) {
list.add(Padding(
padding: const EdgeInsets.all(8.0),
child: TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DrawerTitlePage()));
},
child: Text('${x['name']}',
style: const TextStyle(
color: Colors.white,
),),
),
));
}
});
return list;
}

how to get the id from statefull widget to stateless widget in flutter?

I need to get the id from quizCatId in the category() class to QuizTile() can someone tell me how to solve the issue...
my need is to call subcategory data from firestore which has an quizid and quizcatid and there I have my quizdata so I need to pass both the id to the quizdata to get data from the firestore
class Category extends StatefulWidget {
String quizCatId;
Category(this.quizCatId);
#override
_CategoryState createState() => _CategoryState();
}
class _CategoryState extends State<Category> {
Stream quizStream;
DatabaseService databaseService = new DatabaseService();
Widget quizList() {
return Container(
child: Column(
children: [
StreamBuilder(
stream: quizStream,
builder: (context, snapshot) {
return snapshot.data == null
? Container()
: ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
return QuizTile(
noOfQuestions: snapshot.data.documents.length,
imageUrl:
snapshot.data.documents[index].data['quizImgUrl'],
title:
snapshot.data.documents[index].data['quizTitle'],
desc: snapshot.data.documents[index].data['quizDesc'],
quizid: snapshot.data.documents[index].data["quizId"],
);
});
},
),
],
),
);
}
#override
void initState() {
databaseService.getCatData(widget.quizCatId).then((value) {
quizStream = value;
setState(() {});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: appBar(context),
brightness: Brightness.light,
elevation: 0.0,
backgroundColor: Colors.transparent,
//brightness: Brightness.li,
),
body: SingleChildScrollView(child: quizList()),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CreateCategoryQuiz()));
},
),
);
}
}
class QuizTile extends StatelessWidget {
final String imageUrl, title, quizid, desc, quizcatId;
final int noOfQuestions;
QuizTile({
#required this.title,
#required this.imageUrl,
#required this.desc,
#required this.quizid,
#required this.noOfQuestions,
#required this.quizcatId,
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PlayQuiz(quizid, quizcatId)));
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 14),
height: 150,
margin: EdgeInsets.only(bottom: 8),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
children: [
Image.network(
imageUrl,
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
),
Container(
color: Colors.black26,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
title,
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w500),
),
SizedBox(
height: 4,
),
Text(
desc,
style: TextStyle(
fontSize: 13,
color: Colors.white,
fontWeight: FontWeight.w500),
)
],
),
),
)
],
),
),
),
);
}
}
Hey you have acces to statefulWidget properties form state class by windget property.
All you have to do is ad new parameter in QuizTile constructor and call them
QuizTile(
noOfQuestions: snapshot.data.documents.length,
imageUrl:
snapshot.data.documents[index].data['quizImgUrl'],
title:
snapshot.data.documents[index].data['quizTitle'],
desc: snapshot.data.documents[index].data['quizDesc'],
quizid: snapshot.data.documents[index].data["quizId"],
quizCatId: widget.quizCatId
);

how to use widget value from stateful into stateless

I am having a stuck on transferring the value from the second page to the third page using the value pass from the first page. when I am trying to use the usual way that I am used to calling the data in the stateful widget, it returns an error on undefined.
class restaurantLISTVIEW extends StatefulWidget {
restaurantLISTVIEW({this.category});
final String category;
#override
_restaurantLISTVIEWState createState() => _restaurantLISTVIEWState();
}
within extends state:(working)
FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
'${widget.category}'
),
);
},
);
},),
error on extends stateless widget, return null: (not working)
onTap: ()
{
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(list: list, index: i, category: category)));
}
within extends stateless:(not working)
FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
'$category hellp'
),
);
},
);
},),
The whole 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: ()
{
if(widget.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: [
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: [
],
),
],
),
),
),
);
},
),
),
);
The whole code on the third page:
import 'dart:convert';
import 'package:http/http.dart' as HTTP;
import 'package:flutter/material.dart';
//import 'globals.dart' as globals;
class SarapanPagi extends StatefulWidget {
final List list;
final int index;
final String category;
SarapanPagi({this.index,this.list,this.category});
#override
_SarapanPagiState createState() => _SarapanPagiState();
}
class _SarapanPagiState extends State<SarapanPagi> {
Future<List> getData() async{
var url = 'http://10.0.2.2/foodsystem/breakfastlist.php';
var data = {
'product_type': 'Breakfast',
'product_owner': widget.list[widget.index]['restaurant_id'],
};
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.start,
children: [
//Text("Restaurant's Owner Page"),
Text(widget.list[widget.index]['restaurant_name'], textAlign: TextAlign.center, style: TextStyle(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(),);
},
),
),
SizedBox(height: 10,),
],
),
),
);
}
}
class ItemList extends StatelessWidget {
final List list;
ItemList({this.list});
#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: (){},
child: new Card(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset(
"images/${list[i]['image']}",
width: 150,
height: 150,
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0, bottom: 0),
child:
Column(
children: [
Text(list[i]["product_name"], textAlign: TextAlign.center, style: TextStyle(fontSize: 30),),
Text("Price RM : ${list[i]["product_price"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
RaisedButton(
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(40.0)),
color: Colors.red.shade300,
child: Text("Add to Cart", style: TextStyle(fontWeight: FontWeight.bold),),
onPressed: (){},
)
],
),
),
],
),
/*ListTile(
title: Text(list[i]["product_name"], textAlign: TextAlign.center, style: TextStyle(fontSize: 30),),
leading:
Image.asset(
"images/${list[i]['image']}",
width: 100,
height: 100,
),
subtitle: Text("Price RM : ${list[i]["product_price"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 25),),
),*/
],
),
),
),
);
},
),
),
);
The
You are not using widget.category in restaurantLISTVIEW page but in ItemList widget, that's why you are getting that error.
Adjust your ItemList widget like this
class ItemList extends StatelessWidget {
final List list;
final String category;
ItemList({this.list, this.category});
}
So, your navigation line in ItemList must be
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(list: list, index: i, category: category)));
Also, in SarapanPagi page the variable type of category is not int by String
You are not using widget.category in restaurantLISTVIEW page but in ItemList widget,
The solution that I made is:
this code on the stateful widget class for the second page, needs to be improved by adding the value of the category.
ItemList(list: snapshot.data,)
improved code:
this code forwards the value store in the widget category to the second page from the stateful widget into stateless widget.
ItemList(list: snapshot.data,category: widget.category) :