Pass a parameters to stateful class - flutter

How can I pass a parameters to a stateful class in flutter?
I couldn't pass a parameter in the class as I'm a beginner and don't know the method.
I want to pass data from a list to build the class x times, and display the data in a container.
The text I want to pass is labeled tH.
I hope if someone can pass the argument for me.
My class:
class Thkr extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _ThkrState();
}
}
class _ThkrState extends State<Thkr> {
int Thkr_count = 3;
void _incrementCounter() {
setState(() {
Thkr_count--;
});
}
#override
Widget build(BuildContext) {
return (Column(children: [
Container(
padding: EdgeInsets.all(35),
margin: EdgeInsets.all(20),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 3),
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.lightGreen,
offset: Offset(6.0, 6.0),
),
],
),
child: Text({here I want to pass the data},
style: TextStyle(fontSize: textSize, color: themeli[themei])),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Card(
child: SizedBox(
width: 100,
height: 30,
child: Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.lightGreen,
minimumSize: Size.fromHeight(40), //
),
onPressed: () {
_incrementCounter();
},
child: Text(
'Count',
style: TextStyle(color: themeli[themei]),
),
)),
),
),
Card(
child: SizedBox(
width: 100,
height: 30,
child: Center(
child: Text("$Thkr_count left",
style: TextStyle(
backgroundColor: Colors.white12,
))),
),
),
],
)
]));
}
}

Related

How to make condition in Flutter

There is two files that have similar code, it is add and update area feature, that I decide to make it only one, with using condition.
You can see that two features have similar widgets, only different in texts.
Add Area Feature
Update Area Feature
In my case, when user want to adding area, the UI will display add area feature. When user want to updating area, the UI will display update area feature, but it only from one codebase.
Is it possible to make that kind of condition?
Here I copy paste the whole codes of add area feature. I don't have to copy paste update area because it has the similar codes.
class AddAreaItem extends StatefulWidget {
const AddAreaItem({super.key, this.isUpdate = false});
final bool isUpdate;
#override
State<AddAreaItem> createState() => _AddAreaItemState();
}
class _AddAreaItemState extends State<AddAreaItem> {
//--------- selectedCategory_1 variable
String selectedCategoryArea = '';
#override
Widget build(BuildContext context) {
return Container(
height: 366,
width: 514,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: 25,
),
SizedBox(
width: 434,
height: 42,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
Text(
widget.isUpdate ? 'Add Area' : 'Update Area',
style: heading2(
color: ColorName.blackPrimary,
),
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: InkWell(
child: SvgPicture.asset(
Assets.icons.closeIcon.path,
width: 16,
height: 16,
),
onTap: () => {
Navigator.pop(context),
},
),
)
],
),
),
//----------- TextField Code Area dan Category
SizedBox(
width: 435,
child: Wrap(
alignment: WrapAlignment.spaceAround,
children: [
Wrap(
direction: Axis.vertical,
children: [
Text(
'Area Code',
style: body1(
color: ColorName.blackPrimary,
),
),
SizedBox(
height: 10,
),
SizedBox(
width: 126,
height: 60,
child: TextField(
style: body1(color: ColorName.blackPrimary),
cursorColor: ColorName.blackPrimary,
decoration: InputDecoration(
hintText: 'Area Code',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
focusedBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
borderSide: BorderSide(
color: ColorName.grey,
),
),
),
),
),
],
),
Wrap(
direction: Axis.vertical,
children: [
Text(
'Category Area',
style: body1(
color: ColorName.blackPrimary,
),
),
const SizedBox(
height: 10,
),
Container(
width: 288,
height: 56,
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
side: BorderSide(
style: BorderStyle.solid, color: ColorName.grey),
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
),
child: DropdownButton<String>(
icon: Padding(
padding: const EdgeInsets.only(right: 10, top: 8),
child: SvgPicture.asset(
Assets.icons.dropdownIcon.path,
fit: BoxFit.scaleDown,
),
),
style: body1(color: ColorName.blackPrimary),
items: <String>[
'Block',
'Fining Line',
].map((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
hint: Padding(
padding: const EdgeInsets.only(top: 8, left: 10),
child: Text(
style: body1(color: ColorName.grey),
selectedCategoryArea.isEmpty
? 'Category Area'
: selectedCategoryArea),
),
borderRadius: BorderRadius.circular(10),
underline: const SizedBox(),
isExpanded: true,
onChanged: (value) {
if (value != null) {
setState(() {
selectedCategoryArea = value;
});
}
},
),
),
],
),
],
),
),
//----------- Tombol Add Area dan Cancel
SizedBox(
width: 425,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
SizedBox(
width: 183,
height: 60,
child: OutlinedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
side: MaterialStateProperty.all(
const BorderSide(
color: ColorName.darkBlue,
),
),
),
child: Text(
'Cancel',
style: subtitle1(
color: ColorName.darkBlue,
),
),
onPressed: () {
Navigator.pop(context);
},
),
),
//------------- Tombol add area
SizedBox(
width: 183,
height: 60,
child: OutlinedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
ColorName.darkBlue,
),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
side: MaterialStateProperty.all(
const BorderSide(
color: ColorName.darkBlue,
),
),
),
child: Text(
widget.isUpdate ? 'Add Area' : 'Update Area',
style: subtitle1(
color: ColorName.white,
),
),
onPressed: () {
if (widget.isUpdate) {
AddAreaSuccess().showCustomDialog(context);
} else {
UpdateAreaSuccess().showCustomDialog(context);
}
},
),
),
],
),
),
const SizedBox(
height: 25,
),
],
),
);
}
}
Firstly you need to define from where you know that the screen is updating screen or adding screen. I mean like
class AddAreaItem extends StatefulWidget {
final bool isUpdate;
const AddAreaItem({super.key, this.isUpdate=false});//IT MEANS THAT isUpdate is FALSE by default, but you can define it while creating AddAreaItem
...
}
Then in your widgets you can do like this:
Text(
widget.isUpdate?'Update Area':'Add Area',
//if it is inside Stateless widget then you use isUpdate? instead of widget.isUpdate
style: subtitle1(
color: ColorName.white,
),
),
Inside functions like onPressed you can just use like this:
onPressed: (){
if(widget.isUpdating){
AddAreaSuccess().showCustomDialog(context);
}else{...}
}
You can pass those two values in the properties when rendering this widget. Then check if the properties are null then you are trying to add new data. But if those contains the value then its updating the data.
Something like this
class AreaWidget extends StatefulWidget {
const AreaWidget({super.key, this.areaCode, this.areaName});
final int? areaCode;
final String? areaName;
#override
State<AreaWidget> createState() => _AreaWidgetState();
}
class _AreaWidgetState extends State<AreaWidget> {
#override
Widget build(BuildContext context) {
return Container(
child: Text(widget.areaCode == null ? "Add Area" : "Upate Area"),
);
}
}
You can then check value and make the changes according to the value. Even inside the function as well to call the specific add or update related code.

How can I search the button I made in ListView with Search Bar?

I created a button shape called 'VocabularyWordsButton' and when I try it under a ListView it works just fine. But when I make 100 buttons under ListView, I want to find them via Search Bar. But I don't know how to do it somehow.
What I want to do: I want to distinguish the buttons by filtering the word 'englishWord' among the buttons listed below. When I enter the word in 'englishWord' in Search Bar, I want the buttons containing that word to be filtered.
If I do something like below, only the texts inside are listed, not the button I made.
VocabularyWordsButton.dart
import 'package:being_moroccan/AdHelper.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:sizer/sizer.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:easy_localization/easy_localization.dart';
class VocabularyWordsButton extends StatefulWidget {
VocabularyWordsButton(
{required this.englishWord,
required this.trasncribedWord,
required this.arabicWord,
required this.sound});
final String englishWord;
final String trasncribedWord;
final String arabicWord;
final String sound;
#override
_VocabularyWordsButtonState createState() => _VocabularyWordsButtonState();
}
class _VocabularyWordsButtonState extends State<VocabularyWordsButton> {
AdHelper adHelper = AdHelper();
#override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
adHelper.myLargeBanner.load();
}
bool _canShowButton = true;
void hideWidget() {
setState(() {
_canShowButton = !_canShowButton;
});
}
final AudioCache _audioCache = AudioCache(
prefix: 'audio/',
fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP),
);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: !_canShowButton
? Column(
children: [
Container(
height: 195.h / 6,
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: Container(
height: 100,
child: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(20))),
child: Center(
child: TextButton(
onPressed: () {
hideWidget();
},
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
widget.englishWord,
style: TextStyle(
fontSize: 30.sp / 2,
color: Colors.white),
),
),
),
),
),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.transparent),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(20)),
),
),
),
onPressed: () {
print('cal');
_audioCache.play('${widget.sound}.mp3');
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(2.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'TRANSCRIBED'.tr(),
style: TextStyle(
fontSize: 25.sp / 2,
),
),
Container(
width:
MediaQuery.of(context).size.width /
2,
height: 60.h / 7,
child: Center(
child: Text(
widget.trasncribedWord,
style: TextStyle(
fontSize: 25.sp / 2,
),
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'ARABIC'.tr(),
style: TextStyle(
fontSize: 25.sp / 2,
),
),
Container(
width:
MediaQuery.of(context).size.width /
2,
height: 60.h / 7,
child: Center(
child: Text(
widget.arabicWord,
style: TextStyle(
fontSize: 25.sp / 2,
),
),
),
),
],
),
),
],
),
),
),
],
),
),
),
Container(
height: 100,
child: AdWidget(ad: adHelper.myLargeBanner),
),
],
)
: Container(
width: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.1),
borderRadius: BorderRadius.all(Radius.circular(20))),
child: Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(Colors.transparent),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
),
),
onPressed: () {
hideWidget();
},
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
widget.englishWord,
style:
TextStyle(fontSize: 30.sp / 2, color: Colors.white),
),
),
),
),
),
),
);
}
}
DictionaryScreen.dart
import 'package:sizer/sizer.dart';
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'VocabularyWords/VocabularyWordsButton.dart';
class DictionaryScreen extends StatefulWidget {
static const String id = 'Dictionary_Screen';
const DictionaryScreen({Key? key}) : super(key: key);
#override
_DictionaryScreenState createState() => _DictionaryScreenState();
}
class _DictionaryScreenState extends State<DictionaryScreen> {
TextEditingController editingController = TextEditingController();
// final duplicateItems = List<String>.generate(10000, (i) => "Item $i");
// var items = List<String>();
List<VocabularyWordsButton> words = [
VocabularyWordsButton(
englishWord: 'To pray'.tr(),
trasncribedWord: 'Sella',
arabicWord: 'صْلّى',
sound: 'Sella',
),
VocabularyWordsButton(
englishWord: 'To prefer'.tr(),
trasncribedWord: 'Feddel',
arabicWord: 'فْضّلْ',
sound: 'Feddel',
)
];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
setState(() {});
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: words.length,
itemBuilder: (context, index) {
if (editingController.text.isEmpty) {
return ListTile(
title: Text('${words[index].englishWord} '),
);
} else if (words[index]
.englishWord
.toLowerCase()
.contains(editingController.text)) {
return ListTile(
title: Text('${words[index].englishWord} '),
);
} else {
return Container();
}
}),
),
],
),
),
);
}
}

Flutter : Use function from another file in widget

I'm using flutter and i'm completely a newbie with this framework. I'm trying to use the visibility widget to show and hide a Row.
I'm trying to use this widget when I declare the variable bool _isVisible = false in a stateful or stateless widget, but I have a problem when I want to show and hide the row() through a widget from another dart file. I don't know how to do it. To solve this problem i'm trying to create a dart file for create a function and variable bool _isVisible = false; so that all widgets can access but I am unable to use the bool variable and the function of this dart file in my widgets.
in this picture: ontap in the green circle i want the pink color all the row() with the rating and the button to be hidden.
A screenshot of the issue from my application
P.S: sorry for my english
This is the widget( AnimeMovieDialog ) with the rating section that i want to be hidden (or show) when user tap on the CardAnimeMovie widget.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Tutorial by Woolha.com',
home: AnimeMovieDialog(),
debugShowCheckedModeBanner: false,
);
}
}
class AnimeMovieDialog extends StatefulWidget {
#override
_AnimeMovieDialogState createState() => _AnimeMovieDialogState();
}
class _AnimeMovieDialogState extends State<AnimeMovieDialog> {
double _rating = 1;
double count = 1;
bool _isVisible = true;
void _change() {
setState(() {
_isVisible = !_isVisible;
print("tap succes");
});
}
void _close() {
setState(() {
_isVisible = false;
});
}
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return SafeArea(
child: Visibility(
visible: _isVisible,
child: Stack(children: [
Container(
width: width,
height: height,
decoration: BoxDecoration(color: Color(0xffffff).withOpacity(0.6)),
),
Center(
child: SingleChildScrollView(
child: Container(
width: width / 1.05,
height: height / 1.2,
decoration: BoxDecoration(color: Color(0xff212529)),
child: Column(
children: [
Row(
children: [
Container(
width: width / 1.05,
height: 60,
decoration: BoxDecoration(color: Color(0xff212529)),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding:
const EdgeInsets.fromLTRB(4.0, 5, 35, 0),
child: GestureDetector(
onTap: () {
_close();
},
child: Container(
width: 65,
height: 45,
color: Colors.blue,
child: Icon(Icons.clear,
color: Colors.white)),
),
),
Container(
width: width / 2,
height: height / 2,
child: TextField(
cursorColor: Colors.orange,
style: TextStyle(
color: Colors.white,
),
maxLines: 1,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.orange)),
border: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white)),
hintText: 'Rechercher',
hintStyle:
TextStyle(color: Colors.white),
)),
),
Padding(
padding:
const EdgeInsets.fromLTRB(15, 0, 8, 0),
child: Container(
child: Icon(Icons.search,
color: Colors.white)),
)
],
),
)
],
),
Row(
children: [
Container(
width: width / 1.05,
height: height / 1.5,
child: ListView(
children: [
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie()
],
),
)
],
),
Row(children: [
Column(
children: [
Container(
width: width / 2,
height: height / 11.25,
color: null,
child: Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
25, 0, 0, 0),
child: GFRating(
onChanged: (value) {
setState(() {
_rating = value;
});
},
value: _rating,
size: 25,
color: Colors.orange,
borderColor: Colors.orange,
),
)
],
)),
],
),
Padding(
padding: const EdgeInsets.fromLTRB(35, 0, 8, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: width / 3,
height: height / 18,
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25.0),
topRight: Radius.circular(25.0),
bottomLeft: Radius.circular(25.0),
bottomRight: Radius.circular(25.0))),
child: TextButton(
style: TextButton.styleFrom(
primary: Colors.blue,
onSurface: Colors.red,
),
onPressed: null,
child: Text('Noter',
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 17)),
),
),
],
),
)
])
],
)),
),
),
]),
),
);
}
}
This is the movie resume (green in the picture)
class CardAnimeMovie extends StatefulWidget {
#override
_CardAnimeMovieState createState() => _CardAnimeMovieState();
}
class _CardAnimeMovieState extends State<CardAnimeMovie> {
// bool _visible = false;
// void ratechange() {
// setState(() {
// _visible = !_visible;
// });
// }
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Padding(
padding: const EdgeInsets.all(2.0),
child: GestureDetector(
onTap: () {
ratechange();
},
child: Container(
width: width / 5,
height: height / 3.2,
decoration: BoxDecoration(color: Color(0xff272824)),
child: Row(
children: [
Column(children: [
Container(
width: width / 2.1,
height: height / 3.2,
child: Image.network(
'https://image.noelshack.com/fichiers/2014/31/1406628082-btlbdfqiyaasamj.jpg',
fit: BoxFit.cover,
),
)
]),
Column(children: [
Container(
width: width / 2.15,
height: height / 3.2,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.white, width: 0.5),
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(15, 5, 0, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
children: [
Text(
'Titre : oeuvre',
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 18,
),
)
],
),
SizedBox(
height: 0.5,
),
Row(
children: [
Text(
'Auteur : XXXX',
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 18,
),
)
],
),
SizedBox(height: 7),
Row(
children: [
Container(
width: width / 2.5,
height: height / 5,
child: Text(
"Résume : Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,",
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 18,
),
),
)
],
)
],
),
),
)
])
],
)),
),
);
}
}
You can give function to another dart file and with this you can invoke function in another dart file.
For example:
class AnotherWidget extends StatelessWidget{
final Function myFunction;
AnotherWidget ({this.myFunction});
#override
Widget build(BuildContext context) {
return FlatButton(onPressed: myFunction,....);
}

How to generate new route to the new stfull widget when user created new container?

I am currently developing an app which people can save their receipt in it, I shared home screen below,initial time It will be empty, as soon as user add new menu, it will get full with menu, After user added new menu, the should be able to click the menu container, and access to new screen for example, İn home screen I created container which called "CAKES", the cakes screen should be created, if I created another menu in my home screen It should also created too, I currently menu extanded screen as a statefull widget already, you can see below, but my question is How can I create this page for spesific menu's , How can I store them, in list, in map etc, Lastly, I dont want user information dissapear, I know I have to use database, but I want to use local database, How can I handle with that, Have a nice day...
import 'package:flutter/material.dart';
import 'package:lezzet_kitabi/add_menu_screen.dart';
import 'package:lezzet_kitabi/constants.dart';
import 'package:lezzet_kitabi/widgets.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({this.newMenuName,this.imagePath});
final imagePath;
final newMenuName;
static String id="homeScreen";
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Widget buildBottomSheet(BuildContext context)=>AddMenuScreen(buttonText: "Menü Ekle",route: HomeScreen,);
void initState(){
super.initState();
if (widget.newMenuName!=null && widget.imagePath!=null){
Widget newMenu=MenuCard(newMenuName: widget.newMenuName,imagePath: widget.imagePath);
menuCards.insert(0,newMenu);
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: kColorTheme1,
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
title:TitleBorderedText(title:"SEVIMLI YEMEKLER", textColor: Color(0xFFFFFB00)),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage(kCuttedLogoPath),
),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(kBGWithLogoOpacity),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.count(
crossAxisCount: 2,
children:menuCards,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
boxShadow:[
BoxShadow(
color: Colors.black.withOpacity(1),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0,4),
),
],
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route: "homeScreen",),
);
},
child: TitleBorderedText(title: "LEZZET GRUBU EKLE",textColor: Colors.white,)
),
),
),
],
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:lezzet_kitabi/screens/home_screen.dart';
import 'package:lezzet_kitabi/widgets.dart';
import 'constants.dart';
import 'dart:math';
class AddMenuScreen extends StatefulWidget {
AddMenuScreen({#required this.buttonText, #required this.route});
final route;
final String buttonText;
static String id="addMenuScreen";
#override
_AddMenuScreenState createState() => _AddMenuScreenState();
}
class _AddMenuScreenState extends State<AddMenuScreen> {
int selectedIndex=-1;
Color _containerForStickersInactiveColor=Colors.white;
Color _containerForStickersActiveColor=Colors.black12;
final stickerList= List<String>.generate(23, (index) => "images/sticker$index");
String chosenImagePath;
String menuName;
int addScreenImageNum;
void initState(){
super.initState();
createAddScreenImageNum();
}
void createAddScreenImageNum(){
Random random =Random();
addScreenImageNum = random.nextInt(3)+1;
}
#override
Widget build(BuildContext context) {
return Material(
child: Container(
color: kColorTheme9,
child: Container(
height: 400,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(40),topLeft: Radius.circular(40)),
),
child:Padding(
padding:EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color: kColorTheme2,
borderRadius: BorderRadius.circular(90)
),
child: TextField(
style: TextStyle(
color: Colors.black,
fontFamily:"Graduate",
fontSize: 20,
),
textAlign: TextAlign.center,
onChanged: (value){
menuName=value;
},
decoration: InputDecoration(
border:OutlineInputBorder(
borderRadius: BorderRadius.circular(90),
borderSide: BorderSide(
color: Colors.teal,
),
),
hintText: "Menü ismi belirleyin",
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.2),
fontFamily: "Graduate",
),
),
),
),
SizedBox(height: 20,),
Text(" yana kadırarak menünüz icin bir resim secin",textAlign: TextAlign.center,
style: TextStyle(fontFamily: "Graduate", fontSize: 12),),
SizedBox(height: 20,),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: stickerList.length,
itemBuilder: (context,index){
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: index == selectedIndex ?
_containerForStickersActiveColor :
_containerForStickersInactiveColor,
),
child:FlatButton(
child: Image(
image: AssetImage("images/sticker$index.png"),
),
onPressed: (){
setState(() {
selectedIndex = index;
});
},
),
);
}
),
),
SizedBox(height: 20,),
Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(90),
),
child: FlatButton(
onPressed: (){
widget.route=="homeScreen"?Navigator.push(context, MaterialPageRoute(builder: (context)=>HomeScreen(newMenuName: menuName,imagePath: "images/sticker$selectedIndex.png")))
:Navigator.push(context, MaterialPageRoute(builder: (context)=>MenuExtension(menuExtensionName: menuName)),
);
},
child: Text(widget.buttonText, style: TextStyle(fontSize: 20, color: Colors.white,
fontFamily: "Graduate", fontWeight: FontWeight.bold),),
),
),
],
),
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'dart:math';
import 'add_menu_screen.dart';
import 'package:bordered_text/bordered_text.dart';
import 'package:lezzet_kitabi/screens/meal_screen.dart';
import 'constants.dart';
List<Widget> menuExtensionCards=[EmptyMenu()];
List<Widget> menuCards=[EmptyMenu()];
class MenuCard extends StatelessWidget {
MenuCard({this.newMenuName, this.imagePath});
final newMenuName;
final imagePath;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: FlatButton(
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>MenuExtension(menuExtensionName: newMenuName,)));
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(0.5),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 10,),
Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.5),
borderRadius: BorderRadius.circular(90),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
newMenuName,
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Graduate',
fontWeight: FontWeight.bold),
),
),
),
Expanded(
child: Padding(
padding:EdgeInsets.all(5),
child: Image(
image: AssetImage(
imagePath
),
),
),
),
],
),
),
),
);
}
}
class EmptyMenu extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route:"homeScreen"),
);
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.black12.withOpacity(0.1),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.add_circle_outline_outlined,size: 100,color: Colors.grey.shade400,),
],
),
),
),
);
}
}
class MenuExtension extends StatefulWidget {
MenuExtension({this.menuExtensionName});
final String menuExtensionName;
#override
_MenuExtensionState createState() => _MenuExtensionState();
}
class _MenuExtensionState extends State<MenuExtension> {
Widget buildBottomSheet(BuildContext context)=>AddMenuScreen(buttonText: "Tarif Ekle",route: MealScreen,);
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
title:BorderedText(
child:Text(
widget.menuExtensionName,
style: TextStyle(
color: Color(0XFFFFFB00),
fontSize: 30,
fontFamily: "Graduate"
),
),
strokeWidth: 5,
strokeColor: Colors.black,
),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage("images/cuttedlogo.PNG"),
),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/logoBGopacity.png"),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.count(
crossAxisCount: 2,
children:menuExtensionCards,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
boxShadow:[
BoxShadow(
color: Colors.black.withOpacity(1),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0,4),
),
],
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Tarif Ekle", route:"mealScreen"),
);
},
child: BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text("Tarif Ekle",style: TextStyle(
color: Colors.white,
fontFamily:'Graduate',
fontSize:30,
),
),
),
),
),
),
],
)
],
),
),
),
);
}
}
class TitleBorderedText extends StatelessWidget {
TitleBorderedText({this.title, this.textColor});
final Color textColor;
final String title;
#override
Widget build(BuildContext context) {
return BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text(title,style: TextStyle(
color: textColor,
fontFamily:'Graduate',
fontSize:30,
),
),
);
}
}

trying to add to bag and to update prices and cups

I am trying to do this test TODOs: but i have been have issuses pls help: i am trying to Uncomment the _confirmOrderModalBottomSheet() method to show summary of order, Uncomment the setState() function to clear the price and cups, and Change the 'price' to 0 when this button is clicked Increment the _cupsCounter when 'Add to Bag' button is clicked, and to Call setState((){}) method to update both price and cups counter when 'Add to Bag' button is clicked
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Coffee Test',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.white,
),
home: MyHomePage(title: 'Coffee Test'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedPosition = -1;
String _coffeePrice ="0";
int _cupsCounter =0;
int price = 0;
String _currency ="₦";
static const String coffeeCup ="images/coffee_cup_size.png";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: FlatButton(
onPressed: (){
//TODO: Uncomment the _confirmOrderModalBottomSheet() method to show summary of order
//_confirmOrderModalBottomSheet(totalPrice: "$_currency$price", numOfCups: "x $_cupsCounter");
},
child: Text("Buy Now",style: TextStyle(color: Colors.black87),),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18.0), side: BorderSide(color: Colors.blue))
),
actions: [
InkWell(
onTap: () {
//TODO: Uncomment the setState() function to clear the price and cups
//TODO: Change the 'price' to 0 when this button is clicked
setState(() {
this.price = -1;
this._cupsCounter = 0;
});
Icon(Icons.clear);
}),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Container(
height: double.maxFinite,
alignment: Alignment.center,
child: Text("$_cupsCounter Cups = $_currency$price.00", style: TextStyle(fontSize: 18),),
),
)
],
),
body: Padding(padding: EdgeInsets.all(20), child: _mainBody(),) // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _mainBody(){
return SingleChildScrollView(
child: Container(
height: double.maxFinite,
width: double.maxFinite,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 0,
child: Stack(
children: [
Container(
width: double.maxFinite,
height: 250,
margin: EdgeInsets.only(left: 50, right: 50, bottom: 50, top: 60),
decoration: BoxDecoration(borderRadius:
BorderRadius.all(Radius.circular(180)),
color: Color.fromRGBO(239, 235, 233, 100)),
),
Container(
alignment: Alignment.center,
width: double.maxFinite,
height: 350,
child: Image.asset("images/cup_of_coffee.png", height: 300,),
)
],
)),
Padding(padding: EdgeInsets.all(10),),
Expanded(flex: 0,child: Text("Caffè Americano",
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 30),)),
Padding(padding: EdgeInsets.all(6),),
Expanded(flex: 0, child: Text("Select the cup size you want and we will deliver it to you in less than 48hours",
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 14, color: Colors.black45,),
textAlign: TextAlign.start,),
),
Container(
margin: EdgeInsets.only(top: 30, left: 20),
height: 55,
width: double.maxFinite,
alignment: Alignment.center,
child:Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
RichText(text: TextSpan(
text: _currency,
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 25, color: Colors.black87),
children: [
TextSpan(text: _coffeePrice, style: TextStyle(fontSize: 50, fontWeight: FontWeight.bold))
]
),),
Padding(
padding: EdgeInsets.only(right: 15),
),
ListView.builder(itemBuilder: (context, index){
return InkWell(
child: _coffeeSizeButton(_selectedPosition == index,
index ==0? "S" : index ==1? "M": "L"),
onTap: (){
setState(() {
this._coffeePrice= index ==0? "300" : index ==1? "600": "900";
_selectedPosition = index;
});
},
);
}, scrollDirection: Axis.horizontal,
itemCount: 3, shrinkWrap: true,),
],),
),
Container(
margin: EdgeInsets.only(top: 30),
padding: EdgeInsets.all(10),
width: double.maxFinite,
height: 70,
child: FlatButton(onPressed: (){
//TODO: Currently _cupsCounter only show 1 when this button is clicked.
// TODO: Increment the _cupsCounter when 'Add to Bag' button is clicked'
//TODO: Call setState((){}) method to update both price and cups counter when 'Add to Bag' button is clicked
this._cupsCounter = 1;
this.price += int.parse(_coffeePrice);
}, child: Center(child: Text("Add to Bag",
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),)
,),
color: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)
),
),
)
],
),
),
);
}
Widget _coffeeSizeButton(bool isSelected, String coffeeSize){
return Stack(
children: [
Container(alignment: Alignment.center, width: 55,
child: Text(coffeeSize, style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold,
color: isSelected? Colors.blue: Colors.black45),),),
new Container(
margin: EdgeInsets.only(right: 10),
child: Image.asset(coffeeCup, width:50, color: isSelected ? Colors.blue: Colors.black45,),
decoration: BoxDecoration(border: Border(top: BorderSide(color: isSelected? Colors.blue: Colors.black45,
width: isSelected? 2: 1), left: BorderSide(color: isSelected? Colors.blue: Colors.black45,
width: isSelected? 2: 1), bottom: BorderSide(color: isSelected? Colors.blue: Colors.black45,
width: isSelected? 2: 1), right: BorderSide(color: isSelected ?Colors.blue: Colors.black45 ,
width: isSelected? 2: 1)), borderRadius: BorderRadius.all(Radius.circular(5))),
)
],
);
}
void _confirmOrderModalBottomSheet({String totalPrice, String numOfCups}){
showModalBottomSheet(
context: context,
builder: (builder){
return new Container(
height: 150.0,
color: Colors.transparent, //could change this to Color(0xFF737373),
//so you don't have to change MaterialApp canvasColor
child: new Container(
padding: EdgeInsets.all(10),
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(10.0),
topRight: const Radius.circular(10.0))),
child: Column(
children: [
Container(
child: Text("Confirm Order",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),),
alignment: Alignment.center, height: 30, decoration: BoxDecoration(
), ),
_getEstimate(totalPrice, numOfCups)
],
)),
);
}
);
}
Widget _getEstimate(String totalPrice, String numOfCups){
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Image.asset("images/cup_of_coffee.png", height: 70, width: 50,),
Padding(padding: EdgeInsets.all(10)),
Text(numOfCups, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),),
Padding(padding: EdgeInsets.all(10)),
Text(totalPrice, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),)
],
);
}
}
You're setting 1 to your _cupsCounter instead of adding one to it.
When updating your values, putting the operation i.e _cupsCounter += 1; in setState will update the state of your widget which makes values change in your widgets.
setState((){
_cupsCounter += 1; // make it +=1 instead of =1.
price += int.parse(_coffeePrice);
});
Also you can use setState by putting it after your operation which will update the state of your widget after the operation is done.
_cupsCounter += 1; // make it +=1 instead of =1.
price += int.parse(_coffeePrice);
setState((){});
Full code should look like this.
Container(
margin: EdgeInsets.only(top: 30),
padding: EdgeInsets.all(10),
width: double.maxFinite,
height: 70,
child: FlatButton(onPressed: (){
// Currently _cupsCounter only show 1 when this button is clicked.
// Increment the _cupsCounter when 'Add to Bag' button is clicked'
// Call setState((){}) method to update both price and cups counter when 'Add to Bag' button is clicked
setState((){
_cupsCounter += 1; // make it +=1 instead of =1.
price += int.parse(_coffeePrice);
}); // call setState like this
}, child: Center(child: Text("Add to Bag",
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),)
,),
color: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)
),
),
)