Scroll View Not Responding in flutter - flutter

My Scrollview not Responding, can someone tell what I am missing in code:
Please Suggest me how to add scroll view listener I'm beginner.
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../main.dart';
import 'favourite_articles.dart';
import 'coin_system.dart';
class Settings extends StatefulWidget {
#override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
bool _notification = false;
ScrollController _controller;
#override
void initState() {
super.initState();
checkNotificationSetting();
}
checkNotificationSetting() async {
final prefs = await SharedPreferences.getInstance();
final key = 'notification';
final value = prefs.getInt(key) ?? 0;
if (value == 0) {
setState(() {
_notification = false;
});
} else {
setState(() {
_notification = true;
});
}
}
saveNotificationSetting(bool val) async {
final prefs = await SharedPreferences.getInstance();
final key = 'notification';
final value = val ? 1 : 0;
prefs.setInt(key, value);
if (value == 1) {
setState(() {
_notification = true;
});
} else {
setState(() {
_notification = false;
});
}
Future.delayed(const Duration(milliseconds: 500), () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (BuildContext context) => MyHomePage()));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text(
'More',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,
fontFamily: 'Poppins'),
),
elevation: 5,
backgroundColor: Colors.white,
actions: <Widget>[
IconButton(
icon: Icon(Icons.mail),
color: Colors.black,
tooltip: 'Song Request',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoinSystem(),
),
);
})
],
),
body: Container(
decoration: BoxDecoration(color: Colors.white),
child: SingleChildScrollView(
controller: _controller,
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(0, 20, 0, 10),
child: Image(
image: AssetImage('assets/icon.png'),
height: 50,
),
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(0, 10, 0, 20),
child: Text(
"Version 2.1.0 \n ",
textAlign: TextAlign.center,
style: TextStyle(height: 1.6, color: Colors.black87),
),
),
Divider(
height: 10,
thickness: 2,
),
//ListWheelScrollView(
ListView(
//itemExtent: 75,
shrinkWrap: true,
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavouriteArticles(),
),
);
},
child: ListTile(
leading: Image.asset(
"assets/more/favourite.png",
width: 30,
),
title: Text('Favourite'),
subtitle: Text("See the saved songs"),
),
),
//Song Request Code
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoinSystem(),
),
);
},
child: ListTile(
leading: Image.asset(
"assets/more/songrequest.png",
width: 30,
),
title: Text('Songs Request'),
subtitle: Text("Request your favourite songs"),
),
),
//Song Request Code End
ListTile(
leading: Image.asset(
"assets/more/notification.png",
width: 30,
),
isThreeLine: true,
title: Text('Notification'),
subtitle: Text("Change notification preference"),
trailing: Switch(
onChanged: (val) async {
await saveNotificationSetting(val);
},
value: _notification),
),
],
)
],
),
),
),
//),
);
//);
}
}
So, I have tried SingleChildScrollView, in that I have Container and Listview. But Listview doesn't response on scrolling action in landscape mode.
I have added ScrollController _controller; Do i have to create _controller class that listern the scrolling action?

In my understanding, you want to be able to get 2 scrolling. 1. using SingleChildScrollView and inside that Widget, you want to be able to scroll the bottom layer, thus you use ListView. To make it work, you have to place your ListView inside widget that has certain height. Example this implementation is:
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
SizedBox(child: Text('Upper scrollable'), height: 450),
Divider(
height: 10,
thickness: 2,
),
Container(
height: 350,
child: ListView(
shrinkWrap: true,
children: <Widget>[
Container(
color:Colors.red,
child: SizedBox(child: Text('Bottom scrollable'), height: 450),
),
],
),
)
],
),
),
If you don't want to use 2 scroll, don't use ListView inside SingleChildScrollView.

ListView cannot be wrapped with SingleChildScrollView remove it
surround ListView with Expanded Widget
try one of the two alternatives.

Related

Flutter|Updating a ListView

everyone!
I have a HomeScreen, with this code:
return SafeArea(
child: Scaffold(
body: Stack(
children: [
Padding(
padding: const EdgeInsets.only(left: 8, right: 8),
child: Column(children: [
ActiveTaskInfo(
task: tasks.first,
),
const TextWidget(),
Expanded(child: TasksList()),
const SizedBox(height: 80),
]),
),
BottomBarClass(),
],
),
),
);
TasksList() - ListView.
BottomBarClass() - It is a container with a button inside.
If you return the code itself to the main HomeScreen file, everything works, but if you put it in a separate class and when you add a new item to the list (through the button) nothing happens, but if you press Hot Reload, then the new item in the list is displayed.
Code BottomBarClass():
Positioned(
bottom: 0, left: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
child: Container(
height: 80, width: MediaQuery.of(context).size.width,
color: const Color(0xff070417),
child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Icon(Icons.watch_later, color: Colors.white.withOpacity(0.4)),
IconButton(icon: Icon(Icons.add, color: Colors.white.withOpacity(0.4),), iconSize: 32, onPressed: () async {
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
return TaskAdding();
}));
if (result == true) {
setState(() {
});
}
}),
Icon(Icons.pie_chart_rounded, color: Colors.white.withOpacity(0.4), size: 24,),
],),
),
));
Вот пример GIF: https://gifyu.com/image/Spp1O
TaskAdding():
import 'package:flutter/material.dart';
import '../expansions/task_tags_decorations.dart';
import '../expansions/tasks_data.dart';
class TaskAdding extends StatefulWidget {
const TaskAdding({Key? key}) : super(key: key);
#override
State<TaskAdding> createState() => _TaskAddingState();
}
class _TaskAddingState extends State<TaskAdding> {
late String _addField;
late Widget _selectedValue;
late bool _active;
late int _selectedIndex;
#override
void initState() {
_addField = 'Empty';
_active = false;
_selectedValue = tasks[0].icon;
_selectedIndex = 0;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Add'), backgroundColor: Colors.pink),
body: Column(children: [
Text('Add Task', style: TextStyle(color: Colors.white, fontSize: 24),),
TextField(onChanged: (String value) {
_addField = value;
}),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DropdownButton<Widget>(
value: _selectedValue,
onChanged: (newValue) {
setState(() {
_selectedValue = newValue!;
});
},
items: dropdownItems,
),
ElevatedButton(
onPressed: () {
setState(() {
tasks.addAll({
TaskData(
taskName: _addField,
tagOne: _active
? tasks[0].tagOne
: tasks[1].tagOne,
tagTwo: tagTwoContainer[_selectedIndex],
icon: _selectedValue,
taskTime: '00:32:10',
)
});
decorations.addAll({
TaskTagsDecorations(
iconColor: const Color(0xff7012CF))
});
});
Navigator.of(context).pop(true);
},
child: const Text('Add')),
],
),
Center(
child: ListTile(
title: _active
? Center(
child: tasks[0].tagOne,
)
: Center(child: tasks[1].tagOne),
selected: _active,
onTap: () {
setState(() {
_active = !_active;
});
},
),
),
SizedBox(
height: 52,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: tagTwoContainer.length,
itemBuilder: (context, index) {
var tagTwoList = tasks[index].tagTwo;
return SizedBox(
height: MediaQuery.of(context).size.height, width: 160,
child: ListTile(
visualDensity: VisualDensity.compact,
selected: index == _selectedIndex,
selectedTileColor: Colors.indigo.withOpacity(0.6),
title: Align(
alignment: Alignment.topCenter,
child: tagTwoList),
onTap: () {
setState(() {
_selectedIndex = index;
});
},
),
);
}),
),
],),
);
}
List<DropdownMenuItem<Widget>> get dropdownItems {
List<DropdownMenuItem<Widget>> menuItems = [
DropdownMenuItem(
child: const Icon(Icons.free_breakfast),
value: iconCircle[0],
),
DropdownMenuItem(
child: const Icon(Icons.grade_outlined), value: iconCircle[1]),
DropdownMenuItem(child: const Icon(Icons.gamepad), value: iconCircle[2]),
DropdownMenuItem(
child: const Icon(Icons.face_rounded), value: iconCircle[3]),
];
return menuItems;
}
}
You question is not clear. Try to add TasksList()
My solution:
Navigator.push(context,
MaterialPageRoute(builder: (context) {
return HomeScreen();
}));

How to keep disappearing Flutter Bottom Navigation and AppBar after navigating from subpages

I have a bottom Tab bar in my app for navigation and appbar, from the menu page after adding products in Cart screen there is Continue button when i pressed it take me to Login screen, there a normal login with and otp verification, now when i try to navigate back to menu screen after successfull otp verification, i see Tab bar disappeared and the App bar.
How i can fix this problem
Cart Screen
return Scaffold
....
row
...
Container showOrderConfirmationBtn(BuildContext context) {
return Container(
height: 50.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.transparent, style: BorderStyle.solid, width: 1.0),
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10.0),
),
child: FlatButton(
onPressed: () {
isLoggedIn == false
? Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginPage()))
: Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CarConfirmationCompletePage()));
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
'Continue',
style: TextStyle(
color: Colors.white,
fontFamily: 'BuffetRegular',
fontSize: 13,
letterSpacing: 0.5),
),
],
),
)
],
),
),
);
}
}
Login Screen
return Scafold
....
GestureDetector(
onTap: () async {
final prefs =
await SharedPreferences.getInstance();
final customerData = LoginModel(
mobile: maskFormatter.getUnmaskedText());
final result = await loginServices
.loginCustomer(customerData);
final customerId = result['id'];
if (result['existsFlag'] == '1') {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => OtpVerification(
customerId: customerId)));
} else {
// Registering customer
// Registering customer device info
// and navigating the user to otpverification page
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => OtpVerification(
customerId: customerId)));
}
},
child: Container(
margin: const EdgeInsets.only(right: 20.0),
width: 40,
height: 40.0,
decoration: BoxDecoration(
color: Colors.green.shade300,
borderRadius: BorderRadius.circular(10.0),
),
child: Icon(Icons.arrow_forward_ios),
),
),
Otp Screen
return Scaffold
....
PinEntryTextField(
fieldWidth: 60.0,
showFieldAsBox: true,
onSubmit: (String pin) async {
final prefs = await SharedPreferences.getInstance();
// redirected to menu page
final optData =
OtpModel(customerId: widget.customerId, otp: pin);
final result = await loginServices.otpVerify(optData);
if (result['existsFlag'] == '1') {
// setting customer prefs
prefs.setBool('isLoggedIn', true);
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuPage()));
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: null,
content: Text('неверный код подтверждения '),
);
},
); //end showDialog()
}
// ...............................
// showDialog(
// context: context,
// builder: (context) {
// return AlertDialog(
// title: Text("Pin"),
// content: Text('Pin entered is $pin'),
// );
// },
// ); //end showDialog()
// ...............................
}, // end onSubmit
),
Menu Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:get_it/get_it.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
// ... Constants
import '../constants.dart';
// ... Providers
import '../providers/order_notify.dart';
// ... Models
import '../models/cart_order.dart';
import '../models/menu_model.dart';
// ... API'S
import '../apis/api_response.dart';
import '../apis/menu-api.dart';
// ... Pages
import '../pages/menu_detail.dart';
class MenuPage extends StatefulWidget {
final Products pro;
MenuPage({Key key, this.pro}) : super(key: key);
#override
_MenuPageState createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage> {
ProductApi get productsServices => GetIt.I<ProductApi>();
APIResponse<List<Products>> _apiResponse;
bool _isLoading = false;
void _fetchProducts() async {
setState(() {
_isLoading = true;
});
_apiResponse = await productsServices.getProductsList();
setState(() {
_isLoading = false;
});
}
hasDiscount(product) {
return product.hasDiscount == '1'
? product.priceAfter
: product.hasDiscount == '0'
? product.priceBefore
: product.priceAfter;
}
#override
void initState() {
_fetchProducts();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: ListView(
physics: PageScrollPhysics(),
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: kDefaultPadding, vertical: kDefaultPadding),
child: Text('Меню', style: kStyleHeaders),
),
SizedBox(
height: 10.0,
),
Builder(builder: (_) {
if (_isLoading) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Center(child: null),
);
}
if (_apiResponse.error) {
return Center(child: Text(_apiResponse.errorMessage));
}
if (_apiResponse.data.length == 0) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Center(
child: Text(
'No products has been found..!',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
fontFamily: 'BuffetBold',
color: Colors.black,
),
),
),
);
}
return GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: _apiResponse.data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.72,
mainAxisSpacing: 1.0,
crossAxisSpacing: 1.0,
),
itemBuilder: (context, index) {
var product = _apiResponse.data[index];
return CachedNetworkImage(
imageUrl: product.imageMedium,
imageBuilder: (context, imageProvider) => Column(
children: [
GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetail(
id: product.id,
title: product.title,
description: product.description,
structure: product.structure,
imageLarge: product.imageLarge,
weight: product.weight,
hasDiscount: product.hasDiscount,
priceBefore:
double.parse(product.priceBefore),
priceAfter:
double.parse(product.priceAfter),
isHit: product.isHit,
isNew: product.isNew,
isSpicy: product.isSpicy,
isRecommended: product.isRecommended,
isVegetarian: product.isVegetarian,
attributes: product.attributes),
),
),
child: Container(
alignment: Alignment(-1, 0.9),
child: (product.isNew == '1')
? Image.asset(
'assets/images/new.png',
width: 60.0,
)
: null,
height: 165.0,
width: 165.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
),
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 2.0,
spreadRadius: 0,
offset: Offset(0, 2))
],
),
),
),
Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 10.0),
child: Row(
children: [
Flexible(
child: Text(product.title,
style: kStyleTitle))
],
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
product.weight != null
? product.weight
: '',
style: kStyleWeight),
Text(
product.hasDiscount != '0'
? product.priceBefore
: '',
style: kStyleDiscount),
Container(
margin: EdgeInsets.symmetric(
horizontal: 3, vertical: 0),
height: 30.0,
width: 70.0,
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0),
),
color: kPrimaryColor,
textColor: Colors.white,
padding:
EdgeInsets.symmetric(horizontal: 5.0),
onPressed: () {
// ... Todo
context.read<OrderNotify>().addOrder(
CartOrder(
product: product,
qty: 1,
price: hasDiscount(product)),
);
},
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(hasDiscount(product),
style: kStylePrice),
Icon(
FontAwesomeIcons.rubleSign,
size: 13.0,
color: Colors.white,
)
],
),
),
),
],
),
),
],
),
placeholder: (context, url) => Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation(Color(0xffB81F33)),
),
),
errorWidget: (context, url, error) => Icon(
Icons.error,
size: 40.0,
color: Theme.of(context).primaryColor,
),
);
},
);
}),
],
),
],
),
),
);
}
}
Main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
// ... API'S
import './apis/category-api.dart';
import './apis/menu-api.dart';
import './apis/promotion-api.dart';
import './apis/login-api.dart';
import './apis/ipaddress-api.dart';
import './apis/deviceinfo-api.dart';
import './apis/customer_deviceinfo-api.dart';
// Providers
import './providers/order_notify.dart';
import 'app.dart';
void setupLocator() {
GetIt.I.registerLazySingleton(() => PromotionApi());
GetIt.I.registerLazySingleton(() => CategoriesApi());
GetIt.I.registerLazySingleton(() => ProductApi());
GetIt.I.registerLazySingleton(() => LoginApi());
GetIt.I.registerLazySingleton(() => IPAddressInfo());
GetIt.I.registerLazySingleton(() => DeviceInfo());
GetIt.I.registerLazySingleton(() => CustomerDeviceInfoApi());
}
void setDeviceInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
DeviceInfo deviceServices = GetIt.I<DeviceInfo>();
IPAddressInfo ipServices = GetIt.I<IPAddressInfo>();
prefs.setString('ipAddress', await ipServices.getIPAddress());
prefs.setString('manufacturerModel', await deviceServices.getPhoneInfo());
prefs.setString('deviceVersion', await deviceServices.getPhoneVersion());
prefs.setString('os', await deviceServices.getOperatingSystem());
prefs.setString(
'screenResolution', await deviceServices.getScreenResolution());
prefs.setString('packageOrBundle', await deviceServices.getPackageName());
prefs.setString('appVersion', await deviceServices.getAppVersion());
prefs.setString('isPhysical',
await deviceServices.isPhysicalDevice() == true ? '1' : '0');
prefs.setBool('isLoggedIn', false);
}
void main() {
// ... setup shared prefrences
// ... todo
// ... get device informaton set shared prefrences
// ... todo
// ... Setuploacator
setupLocator();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (ctx) => OrderNotify(),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
),
),
);
setDeviceInfo();
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isStartHomePage = false;
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 3), () {
// If the page has not jump over the jump page
if (!isStartHomePage) {
// Go Home and destroy the current page
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => App(),
),
(Route<dynamic> rout) => false);
isStartHomePage = true;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
'assets/images/stripes_min.jpg',
),
),
),
),
Positioned(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/Buffet_Logo_Trans_min.png',
width: 200.0,
height: 200.0,
),
],
),
),
),
],
),
);
}
}
main.screen
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// ... APP Helpers
import '../helpers/app_helper.dart';
// ... Pages
import '../pages/home_page.dart';
import '../pages/promotions_page.dart';
import '../pages/menu_page.dart';
import '../pages/more_page.dart';
import '../pages/orders_page.dart';
import '../pages/cart.dart';
// ... Providers
import '../providers/order_notify.dart';
// ... Widgets
import '../widgets/badge.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
// Current Index set to 0
int currentTabIndex = 0;
final List<Widget> pages = [
HomePage(
key: PageStorageKey('HomePage'),
),
PromotionsPage(
key: PageStorageKey('PromoPage'),
),
MenuPage(
key: PageStorageKey('MenuOage'),
),
OrdersPage(
key: PageStorageKey('Orderpage'),
),
MorePage(
key: PageStorageKey('Morepage'),
),
Cart(
key: PageStorageKey('CartPage'),
)
];
final PageStorageBucket bucket = PageStorageBucket();
// Current page
Widget currentPage;
void setTabIndex(index) {
setState(() {
currentTabIndex = index;
currentPage = pages[index];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
elevation: 0.0,
leading: InkWell(
onTap: () {
Helper.launchUrl('tel:88007073566');
},
child: Icon(
Icons.call,
color: Colors.black,
size: 25.0,
),
),
title: Text(
'BUFFET',
style: TextStyle(fontSize: 30.0, fontFamily: 'BuffetBold'),
),
centerTitle: true,
actions: [
Container(
margin: EdgeInsets.symmetric(horizontal: 0),
width: 60,
child: Badge(
color: Colors.green,
child: IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Cart()));
},
),
value: context.watch<OrderNotify>().items.length.toString(),
),
)
],
),
body: PageStorage(
child: pages[currentTabIndex],
bucket: bucket,
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
setTabIndex(index);
},
currentIndex: currentTabIndex,
type: BottomNavigationBarType.fixed,
selectedItemColor: Theme.of(context).primaryColor,
selectedFontSize: 0,
unselectedFontSize: 0,
iconSize: 30,
elevation: 0,
backgroundColor: Colors.white,
selectedIconTheme: IconThemeData(size: 28),
unselectedItemColor: Theme.of(context).focusColor.withOpacity(1),
selectedLabelStyle:
Theme.of(context).textTheme.bodyText1.merge(TextStyle(
fontSize: 12,
fontFamily: 'BuffetBold',
)),
unselectedLabelStyle:
Theme.of(context).textTheme.button.merge(TextStyle(
fontSize: 12,
fontFamily: 'BuffetBold',
)),
showUnselectedLabels: true,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home_outlined,
),
label: 'Главная',
),
BottomNavigationBarItem(
icon: Icon(Icons.card_giftcard_outlined),
label: 'Акции',
),
BottomNavigationBarItem(
icon: Icon(Icons.restaurant),
label: 'Меню',
),
BottomNavigationBarItem(
icon: Icon(Icons.av_timer),
label: 'Заказы',
),
BottomNavigationBarItem(
icon: Icon(Icons.menu),
label: 'Еще',
)
],
),
);
}
}
App.dart
import 'package:flutter/material.dart';
// ... Constants
import 'constants.dart';
// ... Screens
import './screens/main_screen.dart';
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Buffet',
theme: ThemeData(
primaryColor: kPrimaryColor,
fontFamily: 'Buffet',
),
home: MainScreen(),
);
}
}
Your mistake is that you pushed MenuPage to stack in OtpScreen
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuPage()));
You should pop the otp page or navigate to MainScreen that contains your PageStorage

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 General dialog box - set state not working

I have an issue with my General Dialog Box. I would like to display a star. Then I would like to change it state when the star is taped and replace the icon by a yellow Star.
But is does not work. The Dialog Box is not refreshed so the icon is not changing. Please, can you look at the source code below and point me into the right direction please?
Many thanks.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:date_time_picker/date_time_picker.dart';
import 'package:gtd_official_sharped_focused/snackbar.dart';
String _isImportantInboxTask ;
String _isUrgentInboxTask ;
String inboxTaskDisplayed;
String isImportant = "false" ;
String isUrgent = "false" ;
String myProjectName ;
var taskSelectedID;
//---------------
//String _initialValue;
//_-----------------
var documentID;
var textController = TextEditingController();
var popUpTextController = TextEditingController();
class Inbox extends StatefulWidget {
Inbox({Key key}) : super(key: key);
#override
_InboxState createState() => _InboxState();
}
class _InboxState extends State<Inbox> {
GlobalKey<FormState> _captureFormKey = GlobalKey<FormState>();
bool isOn = true;
#override
Widget build(BuildContext context) {
void showAddNote() {
TextEditingController _noteField = new TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog(
content: Container(
width: MediaQuery.of(context).size.width / 1.3,
height: MediaQuery.of(context).size.height / 4,
child: Column(
children: [
TextField(
controller: _noteField,
maxLines: 4,
decoration: InputDecoration(
border: const OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.black, width: 1.0),
),
),
),
SizedBox(height: 10),
Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
child: MaterialButton(
minWidth: MediaQuery.of(context).size.width / 1.5,
onPressed: () {
Navigator.of(context).pop();
CollectionReference users = FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('allTasks');
users
.add({'task_Name': _noteField.text,'task_Status': 'Inbox' })
.then((value) => print("User Document Added"))
.catchError((error) =>
print("Failed to add user: $error"));
},
padding: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
child: Text(
'Add Note',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
),
);
});
}
return Scaffold(
appBar: new AppBar(
title: new Text('Inbox Page'),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add_circle_outline,
color: Colors.white,
),
onPressed: () {
showAddNote();
// do something
},
),
],
),
drawer: MyMenu(),
backgroundColor: Colors.white,
body: Column(
//mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: MediaQuery.of(context).size.height / 1.4,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('allTasks')
.where('task_Status', isEqualTo: 'Inbox')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: snapshot.data.docs.map((document) {
return Wrap(
children: [Card(
child: SwipeActionCell(
key: ObjectKey(document.data()['task_Name']),
actions: <SwipeAction>[
SwipeAction(
title: "delete",
onTap: (CompletionHandler handler) {
CollectionReference users = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('allTasks');
users
.doc(document.id)
.delete()
.then((value) => print("Note Deleted"))
.catchError((error) => print(
"Failed to delete Task: $error"));
},
color: Colors.red),
],
child: Padding(
padding: const EdgeInsets.all(0.0),
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
minWidth: leadingIconMinSize,
minHeight: leadingIconMinSize,
maxWidth: leadingIconMaxSize,
maxHeight: leadingIconMaxSize,
),
child: Image.asset('assets/icons/inbox.png'),
),
title: GestureDetector(
child: Text(
//'task_Name' correspond au nom du champ dans la table
document.data()['task_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
// Pour editer task
onDoubleTap: (){
taskSelectedID = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('allTasks')
.doc(document.id);
//Dialog
return showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
barrierColor: Colors.black45,
transitionDuration: const Duration(milliseconds: 20),
pageBuilder: (BuildContext buildContext,
Animation animation,
Animation secondaryAnimation) {
return Scaffold(
appBar: AppBar(
title: Text ('Edit Task'),
leading: InkWell(
child: Icon(Icons.close),
onTap:(){Navigator.of(context).pop();}
),
actions: [Padding(
padding: const EdgeInsets.fromLTRB(0, 0,16.0,0),
child: InkWell(
child: Icon(Icons.save),
onTap: () {
final loFormInbox = _captureFormKey
.currentState;
if (loFormInbox.validate()) {
loFormInbox.save();
CollectionReference users = FirebaseFirestore
.instance
.collection(
'Users')
.doc(FirebaseAuth
.instance
.currentUser.uid)
.collection(
'allTasks');
users
.add({
'task_Name': _valueTaskNameSaved,
})
.then((value) =>
print(
"Task Created"))
.catchError((
error) =>
print(
"Failed to add task: $error"));
showSimpleFlushbar(
context,
'Task Saved',
_valueTaskNameSaved,
Icons
.mode_comment);
loFormInbox.reset();
isImportant = 'false';
isUrgent = 'false';
}
}
),
)],
),
body: Center(
child: Container(
width: MediaQuery.of(context).size.width - 10,
height: MediaQuery.of(context).size.height - 80,
padding: EdgeInsets.all(20),
color: Colors.white,
child: Column(
children: [
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
initialValue: document.data()['task_Name'],
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 70,
maxLines: 2,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
)),
//Test Energy et Time / Important /urgent
Material(
child:
Container(
// color: Colors.red,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:[
//Important
FlatButton(
child:
InkWell(
child: Container(
// color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
isImportant =="true" ? Icon(Icons.star,color: Colors.orange,) :
Icon(Icons.star_border, color: Colors.grey,),
// Icon(Icons.battery_charging_full),
Text('Important'),
],
)
),
onTap: () {
setState(() {
if (isImportant=='true'){
isImportant = 'false';}
else
{isImportant= 'true';
}
});
},
),
),
RaisedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Close",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
)
//++++++++++++++++
],
),
),
),
);
});
},
),
),
),
),
),
),
]
);
}).toList(),
);
}),
),
],
),
bottomNavigationBar: MyBottomAppBar(), //PersistentBottomNavBar(),
);
}
}
#override
Widget build(BuildContext context){
return _widget();
}
}
Thanks to your solution, I am able to do what I was willing to do. But now, I have an other issue. In the version 1 of my code, I am using this code
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
initialValue: document.data()['task_Name'],
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 70,
maxLines: 2,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
)),
This part was working well. But after the modifications, I am getting an error. The error is about document.
Undefined name 'document'. Try correcting the name to one that is defined, or defining the name.
Please, can you help me with this so I can finalize this page. Thank you
So you want to change the color of icon on clicking it inside dialogBox,
but unfortunately you are using stateless widget Scaffold in return of showGeneralDialog builder so one thing that can possibly help is to make a separate StateFull Widget RatingDialogBox and use that in the builder.
Also instead of InkWell you can use IconButton
I will suggest you to use this package it is great
flutter_rating_bar
also feel free to comment is this doesn't satisfy your need

How to put Search container inside my Home.dart?

I have two dart file which are Home.dart and menuUser.dart. I've been following some tutorial in developing my apps. My problem now is, I don't know how to put my Search bar or container in my Home.dart because I already have appBar inside my menuUser.dart. I figure out if I put appBar inside my Home.dart, my apps will have double tab bar at the top.
Here is my menuUser.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp/model/api.dart';
import 'package:myapp/view/home.dart';
import 'package:myapp/view/budget.dart';
import 'package:myapp/view/locationMap.dart';
import 'package:myapp/view/profile.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MenuUsers extends StatefulWidget {
final VoidCallback signOut;
MenuUsers(this.signOut);
#override
_MenuUsersState createState() => _MenuUsersState();
}
class _MenuUsersState extends State<MenuUsers> {
signOut(){
setState((){
widget.signOut();
});
}
String name = "";
TabController tabController;
getPref()async{
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
name = preferences.getString("name");
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
getPref();
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.pink,
actions: <Widget>[
IconButton(
onPressed: (){
signOut();
},
icon: Icon(Icons.lock_open),
)
],
),
body: TabBarView(
children: <Widget>[
Home(),
Budget(),
LocationMap(),
Profile(),
],
),
bottomNavigationBar: TabBar(
labelColor: Colors.pink,
unselectedLabelColor: Colors.grey,
indicator: UnderlineTabIndicator(
borderSide: BorderSide(
style: BorderStyle.none
)
),
tabs: <Widget>[
Tab(
icon: Icon(Icons.home),
text: "Home",
),
Tab(
icon: Icon(Icons.shopping_basket),
text: "Budget",
),
Tab(
icon: Icon(Icons.map),
text: "Location",
),
Tab(
icon: Icon(Icons.person),
text: "Profile",
)
],
),
),
);
}
}
and here is my Home.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp/model/UserAttractionModel.dart';
import 'package:myapp/model/categoryProductModel.dart';
import 'package:myapp/network/network.dart';
import 'package:myapp/view/productDetail.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var loading = false;
List<CategoryProductModel> listCategory = [];
getProductWithCategory() async{
setState(() {
loading = true;
});
listCategory.clear();
final response = await http.get(NetworkUrl.getProductCategory());
if(response.statusCode == 200){
final data = jsonDecode(response.body);
print(data);
setState(() {
for(Map i in data){
listCategory.add(CategoryProductModel.fromJson(i));
}
loading = false;
});
} else {
setState(() {
loading = false;
});
}
}
var filter = false;
List<UserAttractionModel> list =[];
getAttraction()async{
setState(() {
loading = true;
});
list.clear();
final response = await http.get(NetworkUrl.getAttraction());
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print(data);
setState(() {
for (Map i in data) {
list.add(UserAttractionModel.fromJson(i));
}
loading= false;
});
} else {
setState(() {
loading= false;
});
}
}
Future<void> onRefrash() async{
getAttraction();
getProductWithCategory();
setState(() {
filter = false;
});
}
int index = 0;
#override
void initState() {
// TODO: implement initState
super.initState();
getAttraction();
getProductWithCategory();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: loading ? Center(
child: CircularProgressIndicator(),
)
: RefreshIndicator(
onRefresh: onRefrash,
child: ListView(
children: <Widget>[
//Kategori attraction#produk
Container(
height: 50,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: listCategory.length,
itemBuilder: (context,i){
final a = listCategory[i];
return InkWell(
onTap: (){
setState(() {
filter = true;
index = i;
print(filter);
});
},
child: Container(
margin: EdgeInsets.only(left: 20, right: 1),
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.deepOrangeAccent
),
child: Text(
a.categoryName,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
)
),
),
);
},
),
),
filter
? listCategory[index].attraction.length == 0
?
Container(
height: 100,
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Sorry Item on this category not available",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18),
),
],
),
)
: GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
padding: EdgeInsets.all(10),
itemCount: listCategory[index].attraction.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 15,
crossAxisSpacing: 8
),
itemBuilder: (context,i){
final a = listCategory[index].attraction[i];
return InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProductDetail(a)
)
);
},
child: Container(
padding: EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded
(child: Image.network("http://192.168.42.48/myapp/upload/"+ a.image,
width: 100.0,
fit: BoxFit.cover,
height: 180,
),
),
SizedBox(
height: 4,
),
Text("${a.attractionName}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.pink, fontSize: 18),),
Text(" RM ${a.price}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown, fontSize: 16),
),
],
),
),
);
}
) : GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
padding: EdgeInsets.all(10),
itemCount: list.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 15,
crossAxisSpacing: 8
),
itemBuilder: (context,i){
final a = list[i];
return InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProductDetail(a)));
},
child: Container(
padding: EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded
(child: Image.network("http://192.168.42.48/myapp/upload/"+ a.image,
width: 100.0,
fit: BoxFit.cover,
height: 180,
),
),
SizedBox(
height: 4,
),
Text("${a.attractionName}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.pink, fontSize: 18),),
Text(" RM ${a.price}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown, fontSize: 16),
),
],
),
),
);
}
),
//produk
],
),
)
);
}
}
Here is my menu user page and I want to put Search bar at the top of the page probably beside the logout button: