listview.separated flutter showing blank page even it has data - flutter

hi I am new to flutter and dart, i have this issue that the page is showing no data , even though there is data inside listView.seperator , when i check with dubugger , i get data in snapshot.data[index].finishedProductId Or finishedProductName or categoryShortName, but debugger finish it shows blank page, even deleting all i just but Text , still it shows blank page i am giving the code, plz help me. i am giving my code as below thanks in advance. I have marked my website link with start , just for security. Sorry for this.
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class DetailsPage extends StatefulWidget {
final String itemCode;
DetailsPage({Key key, this.itemCode}) : super(key: key);
#override
_DetailsPageState createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
// ignore: missing_return
Future<List<ItemDetails>> _getItemDetails() async {
final response = await http.get(
'https://www.****.com/appfiles/getprodcontent.php?getContent=' +
this.widget.itemCode );
var jsonData = jsonDecode(response.body);
print(jsonData);
List<ItemDetails> itemDet = [];
for (var it in jsonData) {
ItemDetails iDet = ItemDetails(
it['imgPath'],
it['finishedProductId'],
it["finishedProductName"],
it["categoryShortName"],
);
itemDet.add(iDet);
}
print(itemDet.length);
return itemDet;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[200],
appBar: AppBar(
title: Text("Product Details of " + this.widget.itemCode),
),
body: Container(
child: FutureBuilder(
initialData: [],
future: _getItemDetails(),
// ignore: missing_return
builder: (BuildContext context, AsyncSnapshot snapshot) {
//if(snapshot.connectionState == ConnectionState.done){
//if (snapshot.data == null) {
// return Container(
// child: Center(
// child: Text('Loading...'),
/// ));
// } else {
return Column(
children: <Widget> [
SizedBox(
height:200,
child: ListView.seperated(
padding: const EdgeInsets.all(8),
itemCount: snapshot.data.length,
// ignore: missing_return
itemBuilder: (BuildContext context, int index) {
Container (
child:
Center(child: Text("finished product id") ,),
);
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: CircleAvatar(
radius: 50.0,
backgroundImage: NetworkImage(
"https://www.shardaudyogmandir.com/assets/thumbs/javaschatni.png")
!= null ?NetworkImage("https://www.****.com/assets/thumbs/***.png") : Container() ,
),
),
);
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: Text(snapshot.data[index].finishedProductId != null ? snapshot.data[index].finishedProductId: "",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold)),
),
);
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: Text(snapshot.data[index].finishedProductName != null ? snapshot.data[index].finishedProductName: "",
style: TextStyle(color: Colors.black)),
),
);
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: Text(snapshot.data[index].categoryShortName != null ? snapshot.data[index].categoryShortName : "",
style: TextStyle(color: Colors.black)),
),
);
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: RaisedButton(
color: Colors.green[700],
onPressed: () {
//print("press view details");
},
child: const Text('Add To Cart',
style: TextStyle(
fontSize: 20,
color: Colors.white)),
),
),
);
},
//separatorBuilder: (BuildContext context, int index) =>
//const Divider(),
),
)
],
);
//}
//}
}
)
),
);
}
}
class ItemDetails {
final String finishedProductId;
final String finishedProductName;
final String categoryShortName;
//final String rawMaterialName;
final String imgPath;
ItemDetails(this.imgPath, this.finishedProductId, this.finishedProductName,
this.categoryShortName);
}

You need to add return inside Item Builder method like this :
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: CircleAvatar(
radius: 50.0,
backgroundImage: NetworkImage(
"https://www.******.com/assets/thumbs/****.png")
!= null ?NetworkImage("https://www.shardaudyogmandir.com/assets/thumbs/javaschatni.png") : Container() ,
),
),
),
Container (
child:
Center(child: Text("finished product id") ,),
),
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: Text(snapshot.data[index].finishedProductId != null ? snapshot.data[index].finishedProductId: "",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold)),
),
),
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: Text(snapshot.data[index].finishedProductName != null ? snapshot.data[index].finishedProductName: "",
style: TextStyle(color: Colors.black)),
),
),
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: Text(snapshot.data[index].categoryShortName != null ? snapshot.data[index].categoryShortName : "",
style: TextStyle(color: Colors.black)),
),
),
Container(
height: 50,
color: Colors.amber[200],
child: Center(
child: RaisedButton(
color: Colors.green[700],
onPressed: () {
//print("press view details"),
},
child: const Text('Add To Cart',
style: TextStyle(
fontSize: 20,
color: Colors.white)),
),
),
),
],
);
},
And wrap it inside column. I don't know how the UI will be look like but that's the problem from your code. For further information head on Flutter.Dev

Related

News pages doesn't show article or blogs after building apk

I'm creating a flutter project on which it consist of news feature sadly after building an apk and installing it to try in become an empty screen with grey shade, i also try to test it on my phone and this is what happen i dont know where the bugs came from.. please help me
here's the code
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'Article_View.dart';
import 'News_Categories.dart';
import 'helper/Data.dart';
import 'helper/News.dart';
import 'model/Article_Model.dart';
import 'model/CategoryModel.dart';
class NewsHomePage extends StatefulWidget {
#override
_NewsHomePageState createState() => _NewsHomePageState();
}
class _NewsHomePageState extends State<NewsHomePage> {
List<CategoryModel> categories = <CategoryModel>[];
List<ArticleModel> articles = <ArticleModel>[];
bool _loading = true;
//bannerads
late BannerAd _bannerads;
bool _isAdsLoaded = false ;
#override
void initState() {
// TODO: implement initState
super.initState();
categories = getCategories();
getNews();
_initBannerAds();
}
getNews() async {
News newsClass = News();
await newsClass.getNews();
articles = newsClass.news;
setState(() {
_loading = false;
});
}
_initBannerAds(){
_bannerads = BannerAd(
size: AdSize.banner,
// ignore: deprecated_member_use
adUnitId: "ca-app-pub-8634651641429291/4830511818",
listener: BannerAdListener(
onAdLoaded: (ad){
setState(() {
_isAdsLoaded =true;
});
},
onAdFailedToLoad: (ad,error){}
),
request: const AdRequest()
);
_bannerads.load();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
elevation: 0.0,
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text('Stock '),
Text(
'News',
style: TextStyle(
color: Colors.black54,
),
),
],
),
centerTitle:true,
bottom: const PreferredSize(
preferredSize: Size.zero,
child: Text("Powered by news.org")),
),
body: _loading
? Container(
child: const Center(
child: CircularProgressIndicator(),
),
)
: SingleChildScrollView(
child: Container(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
///Categories
Container(
padding: const EdgeInsets.symmetric(horizontal: 22.0),
height: 90.0,
child: Expanded(
child: ListView.builder(
itemCount: categories.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (context, index) {
return CategoryTile(
imageUrl: categories[index].imageAssetUrl,
categoryName: categories[index].categoryName,
);
}),
),
),
///Blogs
Container(
padding: const EdgeInsets.only(top: 16.0),
child: Expanded(
child: ListView.builder(
physics: const ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: articles.length,
itemBuilder: (context, index) {
return BlogTile(
imageURL: articles[index].urlToImage,
title: articles[index].title,
desc: articles[index].description,
url: articles[index].url,
);
},
),
),
),
],
),
),
),
bottomNavigationBar: _isAdsLoaded?SizedBox(
height: _bannerads.size.height.toDouble(),
width: _bannerads.size.width.toDouble(),
child: AdWidget(ad: _bannerads),
)
:const SizedBox(),
);
}
}
class CategoryTile extends StatelessWidget {
final String imageUrl, categoryName;
const CategoryTile({required this.imageUrl, required this.categoryName});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CategoryNews(
category: categoryName.toLowerCase(),
),
),
);
},
child: Container(
margin: EdgeInsets.only(right: 10.0),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: imageUrl != null
? CachedNetworkImage(
imageUrl: imageUrl,
width: 120,
height: 60.0,
fit: BoxFit.cover,
)
: Image.network(
imageUrl,
width: 120.0,
height: 60.0,
fit: BoxFit.cover,
),
),
Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.black26,
borderRadius: BorderRadius.circular(6),
),
width: 120,
height: 60.0,
child: Text(
categoryName,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 18.0,
),
),
),
],
),
),
);
}
}
class BlogTile extends StatelessWidget {
final String imageURL, title, desc, url;
BlogTile(
{required this.imageURL,
required this.title,
required this.desc,
required this.url});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticleView(
blogUrl: url,
)),
);
},
child: Container(
margin: const EdgeInsets.only(bottom: 16.0, left: 10.0, right: 10.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6.0),
child: imageURL != null
? CachedNetworkImage(
imageUrl: imageURL,
)
: Image.network(imageURL),
),
const SizedBox(
height: 8.0,
),
Text(
title,
style: const TextStyle(
//color: Colors.black87,
fontSize: 17.0,
fontWeight: FontWeight.w500,
),
),
const SizedBox(
height: 8.0,
),
Text(
desc,
style: const TextStyle(
//color: Colors.black54,
),
),
],
),
),
);
}
}
and here's the screen shots of the app
[![debugging app][1]][1]
[![build app][2]][2]
[1]: https://i.stack.imgur.com/tvBsG.jpg
[2]: https://i.stack.imgur.com/wOuxS.jpg
Check if this line exists in android/app/src/main/AndroidManifest.xml file. If it doesn't add it right below the package name line. This will grant the app INTERNET permission so it can access it & display the data from the internet.
<uses-permission android:name="android.permission.INTERNET"/>
Flutter by default only adds the INTERNET permission in debug mode. When you build an APK in release mode, you have to explicitly add the permission by including the above line.
More info here.

assigning icon value based on data from flutter sqflite

I'm trying to load the favorite button on my card based on the data from database inside the future builder. while using the following code inside ListView.Builder, is sets the value to true and button click does not change it. I think it is because of FutureBuilder.
txtData.zFavourite == null
? isFavourite[index] = false
: isFavourite[index] = true;
it also requires to initialize the value for isFavourite and if it is assigned outside the widget, I do not get the data from database as it directly loads into the future builder.
how do we assign the value for isFavourite based on the data from the database and change the favourite icon based on the button click?
I also checked this link to handle button clicks for the individual list.
late List<bool> isFavourite = [false, false];
Widget _displayZhesa() {
return FutureBuilder<List<Zhebsa>>(
future: _getZhebsa(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final txtData = snapshot.data![index];
txtData.zFavourite == null
? isFavourite[index] = false
: isFavourite[index] = true;
return Card(
elevation: 10,
color: Colors.white70,
shadowColor: Colors.amber[500],
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(5.0),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.orange[400],
border: Border.all(
color: Colors.amber.shade100,
width: 2,
),
),
child: Center(
child: Text(
sQuery,
style: const TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w500),
),
),
),
Row(
children: <Widget>[
Center(
child: IconButton(
onPressed: () {
setState(() {
isFavourite[index] = !isFavourite[index];
});
},
/* () =>
_setFaviurite(txtData.zFavourite, index), */
icon: Icon(
isFavourite[index]
? Icons.favorite_sharp
: Icons.favorite_border_sharp,
size: 30.0,
color: Colors.redAccent,
),
),
),
Expanded(
child: ListTile(
title: const Text('ཞེ་ས།'),
subtitle: Text(txtData.zWord), //ཞེ་སའི་ཚིག
),
),
Container(
padding: const EdgeInsets.only(right: 20),
child: IconButton(
onPressed: () {
isPlayingPronunciation
? stopPronunciation()
: _playPronunciation(
'${txtData.zPronunciation}');
setState(() {
isPlayingPronunciation =
!isPlayingPronunciation;
});
},
icon: Icon(
isPlayingPronunciation
? Icons.stop_circle_outlined
: Icons.volume_up,
size: 50.0,
color: Colors.blue,
),
),
),
],
),
Container(
padding: const EdgeInsets.only(left: 30.0),
child: ListTile(
title: const Text('དཔེར་བརྗོད།'),
subtitle: SelectableText('${txtData.zPhrase}'),
),
),
],
),
);
},
);
} else {
return const Text('No Data');
}
});
}

Flutter - codes not working correctly after putting inside setState

I am trying to add to an array list after user clicked. I am using InkWell, onTap function.
child: InkWell(
onTap: () {
if (tempArray.contains(entries[index].toString())) {
tempArray.remove(entries[index].toString());
print(tempArray.toList().toString());
} else {
tempArray.add(entries[index].toString());
print(tempArray.toList().toString());
}
My debug console is printing these out,
enter image description here
However, when i put the codes inside a setState, this is what got printed
child: InkWell(
onTap: () {
setState(() {
if (tempArray.contains(entries[index].toString())) {
tempArray.remove(entries[index].toString());
print(tempArray.toList().toString());
} else {
tempArray.add(entries[index].toString());
print(tempArray.toList().toString());
}
});
enter image description here
What i am trying to do, is to show/hide the 'trailing' icon in the ListTile, based on whatever user had selected the particular item.
My full codes (without the setState) are as follows,
import 'package:flutter/material.dart';
class Personal1Redo extends StatefulWidget {
#override
_Personal1RedoState createState() => _Personal1RedoState();
}
class _Personal1RedoState extends State<Personal1Redo> {
#override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
List<String> entries = [
'Residental Loan',
'Personal Loan',
'Car Loan',
'Renovation Loan',
'Savings Account',
];
List<String> tempArray = [];
final heading = Column(
children: [
const SizedBox(
height: 40,
),
SizedBox(
height: (mediaQuery.size.height - mediaQuery.padding.top) * 0.1,
child: const Align(
alignment: Alignment.center,
child: Text(
'What do you aspire to do?',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
),
const SizedBox(
height: 20,
),
],
);
return Scaffold(
appBar: AppBar(
title: Text('Borrower redo'),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
heading,
ListView.builder(
shrinkWrap: true,
itemCount: entries.length,
itemBuilder: (ctx, index) {
return Container(
width: mediaQuery.size.width * 0.9,
padding: const EdgeInsets.all(15),
child: InkWell(
onTap: () {
if (tempArray.contains(entries[index].toString())) {
tempArray.remove(entries[index].toString());
print(tempArray.toList().toString());
} else {
tempArray.add(entries[index].toString());
print(tempArray.toList().toString());
}
},
child: Card(
margin: const EdgeInsets.all(10),
elevation: 8,
child: ListTile(
title: Text(
entries[index],
style: TextStyle(
color: Colors.grey.shade800,
fontSize: 20,
),
textAlign: TextAlign.center,
),
trailing: tempArray.contains(entries[index])
? Icon(Icons.check_box_outline_blank_outlined)
: null,
),
),
),
);
})
],
),
),
);
}
}
Any helps and guidance is very much appreciated, thanks!!
Define variables and functions outside build method.
As setState method, calls build, every time it is called.
Like this :
import 'package:flutter/material.dart';
class Personal1Redo extends StatefulWidget {
#override
_Personal1RedoState createState() => _Personal1RedoState();
}
class _Personal1RedoState extends State<Personal1Redo> {
List<String> entries = [
'Residental Loan',
'Personal Loan',
'Car Loan',
'Renovation Loan',
'Savings Account',
];
List<String> tempArray = [];
getHeadingWidget(BuildContext context) {
return Column(
children: [
const SizedBox(
height: 40,
),
SizedBox(
height: (mediaQuery!.size.height - mediaQuery.padding.top) * 0.1,
child: const Align(
alignment: Alignment.center,
child: Text(
'What do you aspire to do?',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
),
const SizedBox(
height: 20,
),
],
);
}
#override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return Scaffold(
appBar: AppBar(
title: Text('Borrower redo'),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
getHeadingWidget(context),
ListView.builder(
shrinkWrap: true,
itemCount: entries.length,
itemBuilder: (ctx, index) {
return Container(
width: mediaQuery.size.width * 0.9,
padding: const EdgeInsets.all(15),
child: InkWell(
onTap: () {
if (tempArray.contains(entries[index].toString())) {
tempArray.remove(entries[index].toString());
print(tempArray.toList().toString());
} else {
tempArray.add(entries[index].toString());
print(tempArray.toList().toString());
}
},
child: Card(
margin: const EdgeInsets.all(10),
elevation: 8,
child: ListTile(
title: Text(
entries[index],
style: TextStyle(
color: Colors.grey.shade800,
fontSize: 20,
),
textAlign: TextAlign.center,
),
trailing: tempArray.contains(entries[index])
? Icon(Icons.check_box_outline_blank_outlined)
: null,
),
),
),
);
})
],
),
),
);
}
}

Search results and then disappear using stream

I was trying o create search engine. It was working well when I had only one stream but I then tried to merge 2 streams now it shows for some milliseconds then disappears. I do not know what can cause that or anything I did wrong
Below is my code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:tembea/components/search_engine.dart';
import 'package:tembea/screens/user/view_activity.dart';
import 'package:async/async.dart' show StreamGroup;
class SearchDashboard extends StatefulWidget {
const SearchDashboard({Key? key}) : super(key: key);
#override
_SearchDashboardState createState() => _SearchDashboardState();
}
class _SearchDashboardState extends State<SearchDashboard> {
String query = '';
Stream ? streamQuery;
List<Stream<QuerySnapshot>> streams = [];
#override
Widget build(BuildContext context) {
return Column(
children: [
SearchEngine(
onChanged: (value){
setState(() {
if(value.isNotEmpty){
setState(() {
query = value[0].toUpperCase() + value.substring(1);
var firstQuery = FirebaseFirestore.instance.collection('activities')
.where('Type', isGreaterThanOrEqualTo: query)
.where('Type', isLessThan: query + 'z')
.snapshots();
var secondQuery = FirebaseFirestore.instance.collection('activities')
.where('Name', isGreaterThanOrEqualTo: query)
.where('Name', isLessThan: query + 'z')
.snapshots();
streams.add(firstQuery);
streams.add(secondQuery);
streamQuery = StreamGroup.merge(streams);
});
}
});
},
text: query,
),
const SizedBox(
height: 20,
),
const Divider(
height: 20,
color: Colors.green,
),
const SizedBox(
height: 20,
),
streamQuery != null ? StreamBuilder(
stream: streamQuery,
builder:(context, AsyncSnapshot snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.green),
),
);
}
final data = snapshot.requireData;
return SizedBox(
height: MediaQuery.of(context).size.height * 0.50,
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: data.size,
itemBuilder: (context, index){
return GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context){
return ViewActivity(activity: data.docs[index]);
}));
},
child: Column(
children: [
Row(
children: [
const Icon(
IconData(0xe567, fontFamily: 'MaterialIcons'),
color: Colors.green,
),
Text(
data.docs[index]['Name'],
style: GoogleFonts.abel(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(
width: 23
),
Text(
data.docs[index]['Type'],
style: GoogleFonts.abel(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.green
),
),
],
),
const SizedBox(
height: 20,
),
],
),
);
}
),
);
}
) : Center(
child: Text(
'Search for Anything',
style: GoogleFonts.aBeeZee(
textStyle:const TextStyle(
fontSize: 22,
color: Colors.white70,
fontWeight: FontWeight.bold
)
),
),
),
],
);
}
}
Please assist me on this. I have been here the entire day trying to search for solution but cannot find anything

How to add item in a listview from one class to another in Flutter?

I am working on a project in which i have a class which has a row that has two children. Child one contains a TabView with a child class TabViewChild in which i am generating a gridview. On the other hand child two contains a listView. So the problem is, when i click on the gridview item i am passing that item's value to a static list and passing that list to a listview of other class. But i have no idea how to change the state of that class on item clicked or how can i achieve this task in a better way as i am new to Flutter. I want that when a person click on any gridview's item that item appears in the listview simultaneously.
class ItemMenus {
int id;
String code;
String name;
String salePrice;
String photo;
String categoryName;
String percentage;
int quantity;
ItemMenus({this.id, this.code, this.name, this.salePrice, this.photo,
this.categoryName, this.percentage, this.quantity});
ItemMenus.fromJson(Map<String, dynamic> json)
:
id = int.parse(json['id']),
code = json['code'],
name = json['name'],
salePrice = json['sale_price'],
photo = json['photo'],
categoryName = json['category_name'],
percentage = json['percentage'];
#override
String toString() {
return 'ItemMenus{id: $id, code: $code, name: $name, salePrice: $salePrice, photo: $photo, categoryName: $categoryName, percentage: $percentage}';
}
}
import 'package:food_app/model/mdl_item_menus.dart';
class ItemMenuList{
List<ItemMenus> _itmMenuLst = [];
ItemMenuList._();
static final ItemMenuList instanceItmMenuLst = ItemMenuList._();
static ItemMenuList get instance => instanceItmMenuLst;
void addItem(ItemMenus im){
_itmMenuLst.add(im);
}
List<ItemMenus> get list => _itmMenuLst;
#override
String toString() {
return 'ItemMenuList{_itmMenuLst: $_itmMenuLst}';
}
}
import 'package:flutter/material.dart';
import 'package:food_app/database/tables/tbl_categories.dart';
import 'package:food_app/model/list/item_menu_list.dart';
import 'package:food_app/model/mdl_categories.dart';
import 'package:food_app/model/mdl_item_menus.dart';
import 'package:food_app/pos/tab_bar_view.dart';
class EPos extends StatefulWidget{
#override
_EPosState createState() => _EPosState();
}
class _EPosState extends State<EPos> {
final categoryDBHelper = TblCategories.categoriesInstance;
final ItemMenuList instance2 = ItemMenuList.instance;
String _orderType = 'Dine-In', _info = 'Table No. 1', _userName = 'ZiaUddin';
List<Categories> catLst = [];
List<ItemMenus> itmLst = [];
Future getCategories() async {
catLst.clear();
var categories = await categoryDBHelper.getCategories();
categories.forEach((element) {
catLst.add(Categories(
id: element['id'],
categoryName: element['category_name'],
description: element['description'],
userId: element['user_id'],
companyId: element['company_id'],
delStatus: element['del_status']));
});
catLst.forEach((element) {
print(element);
});
return catLst;
}
#override
void initState() {
// TODO: implement initState
super.initState();
// itmLst = instance2.list;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
//#region AppBar
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height * 0.15,
color: Colors.redAccent,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: EdgeInsets.fromLTRB(8, 10, 0, 0),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(20),
color: Colors.red,
),
child: Row(
children: [
Icon(
Icons.arrow_back,
color: Colors.white,
size: 25,
),
Padding(
padding: const EdgeInsets.fromLTRB(4, 8, 10, 8),
child: Text(
_orderType,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
fontFamily: 'Ubuntu',
letterSpacing: 2.0,
),
),
),
],
),
),
Container(
margin: EdgeInsets.fromLTRB(8, 10, 0, 0),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10),
color: Colors.red,
),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 8),
child: Text(
_info,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.amberAccent,
fontFamily: 'Ubuntu',
letterSpacing: 2.0,
),
),
),
),
Container(
margin: EdgeInsets.only(top: 15, right: 5),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(30),
color: Colors.red,
),
child: Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(10, 8, 8, 8),
child: Text(
_userName,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: Colors.white,
fontFamily: 'Ubuntu',
letterSpacing: 1.0,
),
),
),
CircleAvatar(
backgroundColor: Colors.red,
radius: MediaQuery.of(context).size.height * 0.041,
child: CircleAvatar(
radius: MediaQuery.of(context).size.height * 0.04,
backgroundImage: AssetImage('assets/user.png'),
),
),
],
),
),
],
),
),
//endregion
Expanded(
child: Row(
children: [
//# region Menu
Flexible(
flex: 1,
child: Container(
decoration: BoxDecoration(
color: Colors.yellowAccent,
shape: BoxShape.rectangle,
),
child: Column(
children: [
Expanded(
child: Container(
color: Colors.white,
child: FutureBuilder(
future: getCategories(),
builder: (context, snapShot) {
if (snapShot.connectionState ==
ConnectionState.none &&
snapShot.hasData == null) {
return Center(
child: CircularProgressIndicator());
}
return MaterialApp(
debugShowCheckedModeBanner: false,
home: DefaultTabController(
length: catLst.length,
child: Scaffold(
backgroundColor: Colors.white,
appBar: PreferredSize(
preferredSize:
Size.fromHeight(kToolbarHeight),
child: Container(
height: MediaQuery.of(context)
.size
.height *
0.1,
child: TabBar(
indicatorColor:
Colors.amberAccent,
isScrollable: true,
tabs: catLst
.map<Widget>((Categories c) {
return Tab(
icon: Icon(
Icons.style,
color: Colors.amberAccent,
size: 15,
),
child: Text(
c.categoryName
.toUpperCase(),
style: TextStyle(
color: Colors.black,
fontWeight:
FontWeight.w400,
),
),
);
}).toList(),
),
),
),
body: TabBarView(
children: catLst.map((Categories c) {
return TabBarViewChild(categoryName:c.categoryName,
callback: (){
setState(() {
instance2.addItem(ItemMenus(name: c.categoryName));
itmLst = instance2.list;
print('I am Callback');
});
},);
}).toList(),
),
),
),
);
}),
),
),
],
),
),
),
//endregion
//# region OrderList
Flexible(
flex: 1,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
),
child: ListView.builder(
itemCount: itmLst.length,
itemBuilder: (context, index){
return ListTile(
title: Text(itmLst[index].name),
);
},
),
),
),
//endregion
],
),
),
],
),
);
}
}
import 'package:flutter/material.dart';
import 'package:food_app/database/tables/tbl_item_menus.dart';
import 'package:food_app/model/list/item_menu_list.dart';
import 'package:food_app/model/mdl_item_menus.dart';
import 'package:food_app/pos/new_sale.dart';
class TabBarViewChild extends StatefulWidget {
String categoryName;
VoidCallback callback;
TabBarViewChild({Key key,#required this.categoryName, this.callback}) : super(key:key);
#override
_TabBarViewChildState createState() => _TabBarViewChildState();
}
class _TabBarViewChildState extends State<TabBarViewChild> {
final ItemMenuList instance1 = ItemMenuList.instance;
List<ItemMenus> itmLst = [];
final itemMenus = TblItemMenus.itemMenusInstance;
Future getSpecificItemMenus() async{
var items = await itemMenus.getSpecificItemMenus(widget.categoryName);
itmLst.clear();
items.forEach((e) {
itmLst.add(ItemMenus(id: e['id'], categoryName: e['category_name'], code: e['code'],
name: e['name'], percentage: e['percentage'], photo: e['photo'], quantity: e['quantity'],
salePrice: e['sale_price']));
});
for (var value in itmLst) {
print(value);
}
return itmLst;
}
#override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.white,
child: FutureBuilder(
future: getSpecificItemMenus(),
builder: (context, snapShot) {
if (snapShot.connectionState == ConnectionState.none
&& snapShot.hasData == null) {
return Center(child: CircularProgressIndicator());
}
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
scrollDirection: Axis.vertical,
itemCount: itmLst.length,
itemBuilder: (context, index){
return Padding(
padding: const EdgeInsets.all(5.0),
child: InkWell(
child: Card(
elevation: 4,
color: Colors.amberAccent,
child: Center(
child: Text(
itmLst[index].name.toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.red,
fontSize: 13,
fontWeight: FontWeight.w700,
fontFamily: 'Ubuntu',
letterSpacing: 1.0,
),
),
),
),
onTap: (){
// Provider.of<ProItemMenus>(context, listen: false).addNewItemInList(ItemMenus(name: itmLst[index].name.toUpperCase()));
instance1.addItem(ItemMenus(categoryName: itmLst[index].name.toUpperCase()));
print(itmLst[index].name.toUpperCase());
},
),
);
}
);
}
),
);
}
}
So the problem now, there are two stateful widgets.
And as we are going to share the data or the state between them, basically we need to have more one stateful Widget which will the parent of them.
This term of is this problem known as State Management.
Currently there are many reknown State Management , such as Provider and Bloc. Reference.
But personally, I recommend to use Provider, which has simple Syntaxes and Concept.