Related
I'm a beginner in Flutter.
I designed this page:
Instead of repeating the entire Listview.builder. I would like to use two instances of custom Listview.builder with two lists, one list for fruits, and the other for vegetables.
As appeared in the above screen, I tried to display vegetables in the vegetables section through the following:
Listview.builder Widget:
import 'package:flutter/material.dart';
import 'package:grocery_store/models/products_list.dart';
import '../utilities/add_product.dart';
import '../utilities/constants.dart';
class ProductsListView extends StatelessWidget {
final String? productImage;
final String? productName;
final String? productCategory;
final String? productPrice;
const ProductsListView({
Key? key,
this.productImage,
this.productName,
this.productCategory,
this.productPrice,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: fruitsList.length,
itemBuilder: (BuildContext context, int index) {
return ClipRect(
child: Container(
width: 140.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
boxShadow: const [
BoxShadow(
blurRadius: 10,
color: Colors.black,
),
],
),
margin: const EdgeInsets.all(10.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 10, 10),
child: Column(
children: [
Image.asset(
fruitsList[index].fruitImage!,
height: 80.0,
width: 90.0,
),
const SizedBox(
height: 15,
),
Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
fruitsList[index].fruitName!,
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
Text(
fruitsList[index].fruitCategory!,
textAlign: TextAlign.left,
style: const TextStyle(
height: 1.5,
color: kDarkGrey,
fontSize: 12.5,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
Row(
children: [
Text(
fruitsList[index].fruitPrice!,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const Spacer(),
const AddProduct(),
],
)
],
),
),
),
);
},
);
}
}
Fruits and vegetables lists:
import '../utilities/constants.dart';
class Fruits {
final String? fruitImage;
final String? fruitName;
final String? fruitCategory;
final String? fruitPrice;
Fruits(
{this.fruitImage, this.fruitName, this.fruitCategory, this.fruitPrice});
}
final Fruits bananas = Fruits(
fruitImage: '${kFruitsImagesAsset}bananas.png',
fruitName: 'Bananas',
fruitCategory: 'Organic',
fruitPrice: '\$4.99',
);
final Fruits apples = Fruits(
fruitImage: '${kFruitsImagesAsset}apples.png',
fruitName: 'Apples',
fruitCategory: 'Organic',
fruitPrice: '\$5.00',
);
final Fruits chikku = Fruits(
fruitImage: '${kFruitsImagesAsset}chikku.png',
fruitName: 'Chikku',
fruitCategory: 'Organic',
fruitPrice: '\$9.00',
);
final Fruits peaches = Fruits(
fruitImage: '${kFruitsImagesAsset}peaches.png',
fruitName: 'Peaches',
fruitCategory: 'Organic',
fruitPrice: '\$12.00',
);
List<Fruits> fruitsList = [bananas, apples, chikku, peaches];
class Vegetables {
final String? vegetableImage;
final String? vegetableName;
final String? vegetableCategory;
final String? vegetablePrice;
Vegetables(
{this.vegetableImage,
this.vegetableName,
this.vegetableCategory,
this.vegetablePrice});
}
final Vegetables okra = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}okra.png',
vegetableName: 'Okra',
vegetableCategory: 'Organic',
vegetablePrice: '\$6.99',
);
final Vegetables peas = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}peas.png',
vegetableName: 'Peas',
vegetableCategory: 'Organic',
vegetablePrice: '\$10.50',
);
final Vegetables potatoes = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}potatoes.png',
vegetableName: 'Potatoes',
vegetableCategory: 'Organic',
vegetablePrice: '\$5.99',
);
final Vegetables taro = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}taro.png',
vegetableName: 'Taro',
vegetableCategory: 'Organic',
vegetablePrice: '\$5.50',
);
List<Vegetables> vegetablesList = [okra, peas, potatoes, taro];
Homepage where I want to display the two lists:
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:grocery_store/models/product_cards_column.dart';
import 'package:grocery_store/utilities/constants.dart';
import 'package:grocery_store/utilities/grocery_text_field.dart';
import '../models/products_cards.dart';
import '../models/products_list.dart';
class GroceryPage extends StatelessWidget {
const GroceryPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var discountPortrait =
MediaQuery.of(context).orientation == Orientation.portrait;
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 1, 0),
child: Row(
children: [
const Text(
'Grocery',
style: kTitleTextStyle,
),
const Spacer(),
ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Image.asset(
'images/apple.jpg',
width: 46.0,
height: 46.0,
fit: BoxFit.cover,
),
),
],
),
),
const SizedBox(height: 10.0),
Row(children: [
GroceryTextField.groceryTextField(
groceryText: 'Search...',
),
const SizedBox(width: 5.0),
Container(
height: 50.0,
width: 50.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18.0),
color: kLightGrey,
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: SvgPicture.asset(
'images/funnel.svg',
semanticsLabel: 'Funnel',
color: kDarkGrey,
),
),
),
]),
const SizedBox(height: 10.0),
Container(
height: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
color: const Color(0xFFE9F9F2),
),
width: double.infinity,
child: Stack(
children: [
Positioned(
bottom: -150,
right: discountPortrait ? -30 : 30,
height: 290,
width: 430,
child: Image.asset(
'${kProductsImagesAsset}lettuce.png',
),
),
Positioned(
top: discountPortrait ? 35 : 15,
left: discountPortrait ? 25 : 100,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Get Up To',
style: kGreenTitleStyle.copyWith(
fontSize: discountPortrait ? 20 : 60,
),
),
Text(
'%10 off',
style: kGreenTitleStyle.copyWith(
fontSize: 40.0,
),
),
],
),
),
],
),
),
Column(
children: const [
ProductCardsRow(
groceryType: 'Fruits',
),
SizedBox(
height: 215,
width: double.infinity,
child: ProductsListView(
),
),
],
),
Column(
children: const [
ProductCardsRow(
groceryType: 'Vegetables',
),
SizedBox(
height: 215,
width: double.infinity,
child: ProductsListView(
),
),
],
),
],
),
),
),
),
);
}
}
Hope someone can help
You can set an other variable in constructor and call it list and pass your Vegetables and Fruits to it like this:
class ProductsListView extends StatelessWidget {
final List list;
const ProductsListView({
Key? key,
required this.list,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return ClipRect(
child: Container(
width: 140.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
boxShadow: const [
BoxShadow(
blurRadius: 10,
color: Colors.black,
),
],
),
margin: const EdgeInsets.all(10.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 10, 10),
child: Column(
children: [
Image.asset(
list is List<Fruits> ? (list[index] as Fruits).fruitImage! : (list[index] as Vegetables).vegetableImage!,
height: 80.0,
width: 90.0,
),
const SizedBox(
height: 15,
),
Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
list is List<Fruits> ? (list[index] as Fruits).fruitName! : (list[index] as Vegetables).vegetableName!,
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
Text(
list is List<Fruits> ? (list[index] as Fruits).fruitCategory! : (list[index] as Vegetables).vegetableCategory!
textAlign: TextAlign.left,
style: const TextStyle(
height: 1.5,
color: kDarkGrey,
fontSize: 12.5,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
Row(
children: [
Text(
list is List<Fruits> ? (list[index] as Fruits).fruitPrice! : (list[index] as Vegetables).vegetablePrice!,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const Spacer(),
const AddProduct(),
],
)
],
),
),
),
);
},
);
}
}
and use it like this:
SizedBox(
height: 215,
width: double.infinity,
child: ProductsListView(
list: vegetablesList,
),
),
SizedBox(
height: 215,
width: double.infinity,
child: ProductsListView(
list: fruitsList,
),
),
Yeah it is pretty straightfroward, just click on the listview.builder method in your project and then click on FLutter Outline on the right hand side of the Android Studio IDE window, like this :
Once you have done that the ListView.Builder will be visible in this tree of widgets. What you need to do is to right click on the widget you want to extract and then click on extract method.
you'll get a dialog asking for the name of the newly created widget :
and a new widget will be created at the bottom of your file.
Just change the parameters for both the listview.builders and it'll look something like this :
Widget build(BuildContext context) {
return CommonList(typeList: fruitslist); // use this to change the list
}
And in the newly created widget you'd need to do the same:
class CommonList extends StatelessWidget {
final List typeList; //add a list parameter
const CommonList({
Key? key, required this.typeList, //request that list parameter
}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: typeList.length, // change the list type
itemBuilder: (BuildContext context, int index) {
return ClipRect(
child: Container(
width: 140.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
boxShadow: const [
BoxShadow(
blurRadius: 10,
color: Colors.black,
),
],
),
margin: const EdgeInsets.all(10.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 10, 10),
child: Column(
children: [
Image.asset(
typeList[index].fruitImage!, //update list to use it everywhere
height: 80.0,
width: 90.0,
),
const SizedBox(
height: 15,
),
Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
typeList[index].fruitName!, //like here
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
Text(
typeList[index].fruitCategory!, //here
textAlign: TextAlign.left,
style: const TextStyle(
height: 1.5,
color: kDarkGrey,
fontSize: 12.5,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
Row(
children: [
Text(
typeList[index].fruitPrice!, //and here again
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const Spacer(),
const AddProduct(),
],
)
],
),
),
),
);
},
);
}
I'm making an on-boarding screen. Everything is working as expected but there is some space above the image as can be seen in the provided image which shouldn't be there. I tried using MediaQuery.removePadding but that didn't help.
Please look at the code and if you can suggest anything please do. I had the same problem in another project in which I'm using Scaffold->Column->Expanded...., I'm hoping the solution for both would be similar.
class OnBoardingScreen extends StatefulWidget {
const OnBoardingScreen({Key? key}) : super(key: key);
static const String id = 'onboard-screen';
#override
State<OnBoardingScreen> createState() => _OnBoardingScreenState();
}
class _OnBoardingScreenState extends State<OnBoardingScreen> {
int _pages = 0;
final _controller = PageController();
final store = GetStorage();
onButtonPressed(context) {
store.write('onBoarding', true);
return Navigator.pushReplacementNamed(context, MainScreen.id);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Stack(
children: [
PageView(
padEnds: false,
controller: _controller,
onPageChanged: ((val) {
setState(() {
_pages = val.toInt();
});
}),
children: [
OnBoardPage(
boardColumn: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
child: Image.asset(
'assets/images/1.png',
fit: BoxFit.fill,
),
),
const Padding(
padding: EdgeInsets.only(left: 16.0, bottom: 10),
child: Text(
'Welcome\nto Fiesto',
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 44,
color: Colors.white),
),
),
const Padding(
padding: EdgeInsets.only(left: 16.0),
child: Text(
'Book restaurants, cafes,\nbanquet halls, marriage halls, etc',
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 22,
color: Colors.white),
),
),
],
),
),
OnBoardPage(
boardColumn: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
child: Image.asset(
'assets/images/2.png',
),
),
const Padding(
padding: EdgeInsets.only(left: 16.0, bottom: 10),
child: Text(
'Fiesto\nParty Services',
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 44,
color: Colors.white),
),
),
const Padding(
padding: EdgeInsets.only(left: 16.0),
child: Text(
'Get all kinds of party services and\nsolutions',
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 22,
color: Colors.white),
),
),
],
),
),
Positioned.fill(
bottom: 180,
child: Align(
alignment: Alignment.bottomCenter,
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSmoothIndicator(
//https://pub.dev/smooth_page_indicator
activeIndex: _pages,
count: 5,
effect: const JumpingDotEffect(
dotHeight: 16,
dotWidth: 16,
jumpScale: .7,
verticalOffset: 15,
dotColor: Colors.grey,
activeDotColor: Colors.yellow,
),
),
],
),
),
),
Positioned(
right: 16,
bottom: 120,
child: TextButton(
child: const Text(
'Skip & Proceed to\nLogin/Signup',
textAlign: TextAlign.end,
style: TextStyle(
color: Color.fromARGB(255, 117, 13, 13),
fontSize: 14,
decoration: TextDecoration.underline,
),
),
onPressed: () {
onButtonPressed(context);
},
),
),
Positioned(
right: 16,
bottom: 50,
width: 150,
height: 50,
child: ElevatedButton(
onPressed: () {
if (_pages == 0) {
_controller.animateToPage(
1,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
} else if (_pages == 1) {
_controller.animateToPage(
2,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
} else if (_pages == 2) {
_controller.animateToPage(
3,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
} else if (_pages == 3) {
_controller.animateToPage(
4,
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
);
} else if (_pages == 4) {
onButtonPressed(context);
}
},
child: _pages <= 3
? const Text(
'Next',
style: TextStyle(fontSize: 22),
)
: const Text(
'Login/Signup',
style: TextStyle(fontSize: 22),
),
),
),
],
),
),
);
}
}
class OnBoardPage extends StatelessWidget {
final Column? boardColumn;
const OnBoardPage({Key? key, this.boardColumn}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: Color.fromARGB(255, 0, 0, 0),
child: boardColumn,
);
}
}
You have this problem because the Column widgets have a default mainAxisAlignment: MainAxisAlignment.center so I am changing it to: mainAxisAlignment: MainAxisAlignment.startAlso my tests on your code indicate the nature of the image is playing a role. Because its works like you want on my images.
Remove SafeArea or assign top: false.
I am trying to create form.
I managed to create every widget in it, but every time I try to open TextFormField I get redirected back to my MainMenuScreen without any error.
I am using BLoC and routes. I think that issue might be related with using named routes.
Issue was not spotted before changing to named routes
MainMenuScreen fragment:
CategoryCard(
categoryName: 'Main dishes',
assetPath: 'assets/images/main_dish.png',
onPressed: () => Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) {
return BlocProvider.value(
value: BlocProvider.of<RecipesBloc>(context)
..add(LoadRecipesEvent())
..category = 'main_dish',
child: RecipesScreen(),
);
})),
),
From MainMenuScreen I redirect to RecipesScreen
Fragment of RecipesScreen with redirect to RecipeCreateForm:
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) {
return RecipeCreateForm();
}),
),
and then I redirect to RecipeCreateForm where I'm using TextFormFields.
Whenever I try to use TextFormField I get redirected back to MainMenuScreen.
class RecipeCreateForm extends StatefulWidget {
#override
_RecipeCreateFormState createState() => _RecipeCreateFormState();
}
class _RecipeCreateFormState extends State<RecipeCreateForm> {
final _recipeNameController = TextEditingController();
final _imageUrl = TextEditingController();
String? _difficultyValue;
late int _ingredientsQuantity;
late int _preparationStepsQuantity;
late List<Ingredient> _ingredientsValues;
late List<PreparationStep> _preparationStepsValues;
late double _preparationTime;
String? _portions;
#override
void initState() {
_ingredientsQuantity = 1;
_preparationStepsQuantity = 1;
_ingredientsValues = [];
_preparationStepsValues = [];
_preparationTime = 0;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(
Icons.arrow_back,
color: Colors.white,
),
),
),
body: Scrollbar(
thickness: 10,
hoverThickness: 2,
child: SingleChildScrollView(
child: Container(
color: Colors.lightGreen.shade100,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Recipe name',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
TextFormField(
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
controller: _recipeNameController,
),
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Image',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
TextFormField(
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
controller: _imageUrl,
),
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Difficulty',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
DropdownButton(
hint: _difficultyValue == null
? Text(
'Select difficulty',
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
)
: Text(
_difficultyValue!,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
),
isExpanded: true,
iconSize: 30.0,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
items: ['Easy', 'Medium', 'Hard'].map(
(val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
},
).toList(),
onChanged: (val) {
setState(
() {
_difficultyValue = val as String;
},
);
},
),
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Preparation time',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
Slider(
value: _preparationTime,
onChanged: (newPreparationTime) {
setState(() => _preparationTime = newPreparationTime);
},
label: _preparationTime.toStringAsFixed(0),
min: 0,
max: 360,
divisions: 24,
),
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Ingredients',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
SizedBox(
height: 175,
child: Scrollbar(
child: ListView.builder(
itemCount: _ingredientsQuantity,
itemBuilder: (context, index) {
return _ingredientRow(index);
}),
),
),
Row(
children: [
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
setState(() {
_ingredientsQuantity++;
});
}),
IconButton(
icon: Icon(Icons.delete),
onPressed: () async {
setState(() {
_ingredientsQuantity = 1;
_ingredientsValues.clear();
});
})
],
),
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Preparation steps',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
Scrollbar(
child: SizedBox(
height: 100,
child: ListView.builder(
shrinkWrap: true,
itemCount: _preparationStepsQuantity,
itemBuilder: (context, index) {
return _preparationStepRow(index);
}),
),
),
Row(
children: [
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
setState(() {
_preparationStepsQuantity++;
});
}),
IconButton(
icon: Icon(Icons.delete),
onPressed: () async {
setState(() {
_preparationStepsQuantity = 1;
_preparationStepsValues.clear();
});
}),
],
),
Padding(
padding: EdgeInsets.only(top: 15),
),
Text(
'Portions',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
DropdownButton(
hint: _portions == null
? Text(
'Select number of portions',
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
)
: Text(
_portions!,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
),
isExpanded: true,
iconSize: 30.0,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontStyle: FontStyle.italic),
items: ['1', '2', '3', '4', '5', '6', '7'].map(
(val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
},
).toList(),
onChanged: (val) {
setState(
() {
_portions = val as String;
},
);
},
),
ElevatedButton(
onPressed: () {
BlocProvider.of<RecipesBloc>(context).add(
AddRecipeEvent(
Recipe(
name: _recipeNameController.text,
image:
'https://www.thespruceeats.com/thmb/dA8o8EZpjJyeocYZNpzfknoKh2s=/4351x3263/smart/filters:no_upscale()/baked-stuffed-potatoes-482217-hero-01-850f2d87fe80403f923e140dbf5f1bf3.jpg',
ingredients: _ingredientsValues,
difficulty: _difficultyValue,
preparationTime: _preparationTime,
preparationSteps: _preparationStepsValues,
type: BlocProvider.of<RecipesBloc>(context)
.category
.toString(),
portions: _portions,
),
),
);
Navigator.of(context).pop();
},
child: Text('Submit'),
),
],
),
),
),
),
);
}
_ingredientRow(int key) {
return IntrinsicHeight(
child: Row(
children: [
Padding(padding: EdgeInsets.only(left: 10)),
SizedBox(
width: 225,
child: TextFormField(
maxLength: 35,
onChanged: (val) {
setState(() {
_onIngredientUpdate(key,name: val);
});
},
),
),
VerticalDivider(
width: 20,
thickness: 1,
color: Colors.black,
indent: 30,
endIndent: 10,
),
SizedBox(
width: 55,
child: TextFormField(
maxLength: 7,
initialValue: '0',
onChanged: (val) {
setState(() {
_onIngredientUpdate(key, quantity: val);
});
},
),
),
Padding(padding: EdgeInsets.only(left: 10)),
DropdownButton(
hint: Text('pcs'),
items: ['pcs', 'ml', 'g'].map(
(val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
},
).toList(),
onChanged: (val) {
setState(() {
_onIngredientUpdate(key,measurement: val.toString());
});
},
)
],
),
);
}
_onIngredientUpdate(int key, {String? name, String? measurement, String? quantity}) {
int foundKey = -1;
_ingredientsValues.forEach((element) {
if (element.id.contains(key.toString())) {
foundKey = key;
}
});
if (-1 != foundKey) {
_ingredientsValues.removeWhere((map) {
return map.id == foundKey.toString();
});
}
Map<String, dynamic> json = {'id': key, 'name': name, 'measurement': measurement, 'quantity':quantity};
_ingredientsValues.add(json as Ingredient);
}
_preparationStepRow(int key) {
return IntrinsicHeight(
child: Row(
children: [
Padding(padding: EdgeInsets.only(left: 10)),
SizedBox(
width: 225,
height: 50,
child: TextFormField(
maxLength: 35,
onChanged: (val) => {
_onPreparationUpdate(key,val)
},
),
),
],
),
);
}
_onPreparationUpdate(int key, String val) {
int foundKey = -1;
_preparationStepsValues.forEach((element) {
if (element.id.contains(key.toString())) {
foundKey = key;
}
});
if (-1 != foundKey) {
_preparationStepsValues.removeWhere((map) {
return map.id == foundKey.toString();
});
}
Map<String, dynamic> json = {'id': key, 'step': val};
_preparationStepsValues.add(json as PreparationStep);
}
}
Issue GIF:
EDIT:
Issue is not related with form. I have replaced whole form with only one field without any logic and issue remains.
It is probably related to named routes.
As I was thinking, issue was related with usage of named routes.
I managed to bypass this issue with using Future.delayed and pushNamedAndRemoveUntil
In main_menu_screen I have created method which I later used to redirect to categories.
void redirectToCategory(BuildContext context, String categoryName) {
Future.delayed(Duration.zero, () {
Navigator.pushNamedAndRemoveUntil(
context,
'/recipeScreen',
(_) => false,
arguments: BlocProvider.value(
value: BlocProvider.of<RecipesBloc>(context)
..add(LoadRecipesEvent())
..category = categoryName,
child: RecipesScreen(),
),
);
});
I am trying to make a align the heading(title) contents with the body that is the list item here. But it is not getting aligned. If I align it and reduce my screen size (I am using flutter web) it gives a render flex. If I use an expanded widget to align it it doesn't get itself aligned with the body (if I reduce it to half my screen). If I maximise my screen it s getting aligned
I want it to fit even I reduce the screen size.
How do I do it?
Here is the image:
Here is my code
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'Postsc.dart';
late List<Post> drivers;
class MyApp extends StatefulWidget {
// to set the root of app.
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage1(),
);
}
}
class MyHomePage1 extends StatefulWidget {
late final String title;
#override
_MyHomePage1State createState() => _MyHomePage1State();
}
class _MyHomePage1State extends State<MyHomePage1> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Center(
child: Text("Customer Table",
style: TextStyle(
fontWeight: FontWeight.w900,
),
),
),
),
body:Container(
child: Column(
children: [
Row(
children: [
const Text('Cid',
style:TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)
),
( SizedBox(width:MediaQuery.of(context).size.width*0.225)),
const Text('Cname',
style:TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)
),
( SizedBox(width:MediaQuery.of(context).size.width*0.20) ),
const Text('Cadd',
style:TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)
),
( SizedBox(width:MediaQuery.of(context).size.width*0.22)),
const Text('Ctype',
style:TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)
),
]
),
Expanded(
child: Container(
child:_buildBody(context),
),
)
],
),
color:const Color(0xFF303030),
),
);
}
// build list view & manage states
FutureBuilder<List<Post>> _buildBody(BuildContext context) {
final HttpService httpService = HttpService();
return FutureBuilder<List<Post>>(
future: httpService.getPosts(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final List<Post>? posts = snapshot.data; //marked
return _buildPosts(context, posts!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}
// build list view & its tile
ListView _buildPosts(BuildContext context, List<Post> posts) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: posts.length,
itemBuilder: (context, index) {
return Container(
height:70,
child: Card(
shadowColor: Colors.white,
color:const Color(0xFF303030),
elevation: 1,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: Container(
child: Text(posts[index].Cid,style: const TextStyle(fontWeight: FontWeight.bold,
color:Colors.white,),),
),
),
Expanded(
child: Container(
child: Text(posts[index].Cname,style: const TextStyle(fontWeight: FontWeight.bold,
color:Colors.white,),),
),),
Expanded(
child: Container(
child: Text(posts[index].Cadd,style: const TextStyle(fontWeight: FontWeight.bold,color:Colors.white,),
),
),
),
Expanded(
child: Container(
child: Text(posts[index].Ctype,style: const TextStyle(fontWeight: FontWeight.bold,color:Colors.white,),
),
),
),
],
),
),
);
},
);
}
}
class HttpService {
Future<List<Post>> getPosts() async {
Response res = await get(
Uri.parse('http://localhost/localconnect/customer_change.php'));
print(res.body);
if (res.statusCode == 200) {
List<dynamic> body = jsonDecode(res.body);
List<Post> posts = body.map(
(dynamic item) => Post.fromJson(item),
).toList();
return posts;
} else {
throw "Unable to retrieve posts.";
}
}
}
Use Expanded instead of using SizedBox and MediaQuery:.
Like so:
Row(
children: [
const Expanded(
child: Text(
'Cid',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
const Expanded(
child: Text(
'Cname',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
const Expanded(
child: Text(
'Cadd',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
const Expanded(
child: Text(
'Ctype',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
],
)
you can try Expanded widget except using of SizedBox
here is some code:
class MyHomePage1 extends StatefulWidget {
late final String title;
#override
_MyHomePage1State createState() => _MyHomePage1State();
}
class _MyHomePage1State extends State<MyHomePage1> {
List l = [
{"number": "1", "name": "warner", "place": 'sydney', "des": 'Regular customer'},
{"number": "1", "name": "warner", "place": 'sydney', "des": 'Regular customer'},
{"number": "1", "name": "warner", "place": 'sydney', "des": 'Regular customer'},
{"number": "1", "name": "warner", "place": 'sydney', "des": 'Regular customer'},
];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Center(
child: Text(
"Customer Table",
style: TextStyle(
fontWeight: FontWeight.w900,
),
),
),
),
body: Container(
child: Column(
children: [
Row(
children: const [
Expanded(
child: Text('Cid',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)),
),
Expanded(
child: Text('Cname',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)),
),
Expanded(
child: Text('Cadd',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)),
),
Expanded(
child: Text('Ctype',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
)),
),
],
),
Expanded(
child: Column(
children: l
.map(
(e) => Row(
children: [
Expanded(
child: Text(
e['number'],
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
Expanded(
child: Text(
e['name'],
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
Expanded(
child: Text(
e['place'],
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
Expanded(
child: Text(
e['des'],
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
color: Colors.white,
),
),
),
],
),
)
.toList(),
),
)
],
),
color: const Color(0xFF303030),
),
);
}
}
i m creating an application in which i have to change the state of a button save the state. and afterwards when that page is open again then the changed state should be displayed.
for example: if i click on the favorite button then its state gets changed from unselected to selected so after this when i closed the app and open it again then the favorite button should be in selected state rather than in unselected state.
please help me out with this issue.
i have used a variable is which the value is stored and then i m checking the condition .
import 'package:EventsApp/Models/EventModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:favorite_button/favorite_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DetailPage extends StatefulWidget {
final String image;
final EventModel value;
const DetailPage({Key key, this.image, #required this.value})
: super(key: key);
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
String eventId;
String userId;
bool isPartcipated = false;
bool isfavorite;
Future<http.Response> participateinEvent() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var uid = prefs.getString('userId');
var eveid = prefs.getString('eventId');
var res = await http.post(
'http://10.0.2.2:8080/eventusermapping/addParticipant/' +
uid +
'/' +
eveid);
print(res.body);
Fluttertoast.showToast(
msg: 'Participation Successful',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
);
}
Future<http.Response> addfavorite() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var uid = prefs.getString('userId');
var eveid = prefs.getString('eventId');
var res = await http
.post('http://10.0.2.2:8080/event/addtoFavorites/' + uid + '/' + eveid);
Fluttertoast.showToast(
msg: 'Added to favorite',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
);
setState(() {
isfavorite = true;
});
}
Future<http.Response> removefavorite() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var uid = prefs.getString('userId');
var eveid = prefs.getString('eventId');
var res = await http.post(
'http://10.0.2.2:8080/event/removeFromFavorites/' + uid + '/' + eveid);
Fluttertoast.showToast(
msg: 'Removed from favorite',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
);
setState(() {
isfavorite = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Color(0xffffffff)),
onPressed: () => Navigator.of(context).pop(),
),
centerTitle: true,
backgroundColor: Colors.lightBlue[900],
elevation: 0.0,
title: new Text("Event Details",
style: const TextStyle(
color: const Color(0xffffffff),
fontWeight: FontWeight.w500,
fontStyle: FontStyle.normal,
fontSize: 19.0)),
),
body: Container(
child: SingleChildScrollView(
child: Column(
children: [
Container(
width: double.infinity,
height: 400.0,
child: Stack(
children: [
Positioned(
top: 0,
left: 0,
right: 0,
bottom: 90,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('${widget.value.coverimg}'),
fit: BoxFit.fitWidth,
),
),
// child: Column(
// children: [
// IconButton(
// icon: Icon(Icons.arrow_back),
// onPressed: () => Navigator.pop(context),
// iconSize: 30.0,
// color: Colors.lightBlue[900],
// ),
// ],
// ),
),
),
Positioned(
top: 270,
left: 20,
right: 20,
bottom: 0,
child: Card(
elevation: 0.5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0),
),
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
'${widget.value.name}',
style: TextStyle(
fontSize: 23.0,
fontWeight: FontWeight.bold,
color: Colors.lightBlue[900]),
),
],
),
Row(
children: [
Icon(
Icons.location_on,
color: Colors.grey,
size: 20,
),
SizedBox(width: 12.0),
Text(
" Kalyan west",
style: TextStyle(
fontSize: 18,
color: Colors.lightBlue[900]),
),
],
),
Row(
children: [
Icon(
Icons.calendar_today,
color: Colors.grey,
size: 20,
),
SizedBox(width: 12.0),
Text(
'${widget.value.date}',
style: TextStyle(
fontSize: 17,
color: Colors.lightBlue[900]),
),
],
),
],
),
),
),
),
],
),
),
Container(
width: double.infinity,
child: Column(
children: [
SizedBox(height: 12.0),
ListTile(
leading: CircleAvatar(
radius: 25,
backgroundImage:
NetworkImage('${widget.value.eventheadphoto}'),
),
title: Text(
'${widget.value.eventheadname}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.lightBlue[900]),
),
subtitle: Text(
"Event Head",
style: TextStyle(fontSize: 17, color: Colors.grey),
),
),
SizedBox(height: 15.0),
Padding(
padding: EdgeInsets.symmetric(horizontal: 18),
child: Text(
'${widget.value.description}',
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 19, color: Colors.lightBlue[900]),
),
),
SizedBox(height: 20.0),
Container(
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 70.0),
child: Center(
child: SizedBox(
width: 190,
child: isPartcipated
? RaisedButton(
onPressed: null,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(30.0)),
color: Colors.grey,
child: Text(
"Participated",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
letterSpacing: 1.5),
),
disabledColor: Colors.black12,
disabledElevation: 1,
disabledTextColor: Colors.black,
)
: RaisedButton(
onPressed: () {
participateinEvent();
setState(() {
isPartcipated = !isPartcipated;
});
},
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(30.0)),
color: Colors.lightBlue[900],
child: Text(
"Participate",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
letterSpacing: 1.5),
),
),
),
),
),
Padding(
padding: EdgeInsets.only(left: 50.0),
child: Container(
decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(50),
// color: Colors.blue,
// border:
// Border.all(width: 1, color: Colors.grey),
),
child: FavoriteButton(
isFavorite: false,
valueChanged: (isfavorite) {
if (isfavorite) {
addfavorite();
} else {
removefavorite();
}
},
), //IconButton(
// iconSize: 35,
// color: Colors.redAccent[400],
// icon: Icon(Icons.favorite_border),
// tooltip: 'Add to Favorite',
// onPressed: () {}),
),
)
],
),
),
SizedBox(height: 30.0)
],
),
)
],
),
),
),
);
}
}
You not storing the button state in addFavourite method.
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('stateOfButton', true);
When you open your app again, you can get the button state like how you get for the userId and eventId.
prefs.getBool('stateOfButton');
I don't know if it's possible to just rewrite the initial value of the variables for the following executions of the app. What is possible to do is to store this values somehow, and load them before loading the screen with the favorite button.
What i would do is to use path provider(https://pub.dev/packages/path_provider) and store something like(lets suppose we are talking about movies)
"user":{
"favorited movies" : [
12
23
]
}
and then before loading the button, checking the movie id is in the user favorited movies array. You can find a good example of how exactly would you store in the complete example in https://flutter.dev/docs/cookbook/persistence/reading-writing-files
If you think about the standard way to deal with State management in your app I suggest you look into BLoC. It requires an initial learning curve with it but it is worth it.
Feel free to find more info in the 'Counter' example on the website
https://bloclibrary.dev/#/gettingstarted
Here is another good talk by Felix, who maintains bloc library
https://www.youtube.com/watch?v=knMvKPKBzGE&t=2327s
you can use this package flutter shared preferences
you should make get and set methods
class StorageService {
Future<String> getTokenAsync() async {
SharedPreferences instances = await getInstanceAsync();
String stringValue = instances.getString(Constant.userToken);
return stringValue; }
Future<void> setTokenAsync(String token) async {
SharedPreferences instances = await getInstanceAsync();
instances.setString(Constant.userToken, token); } }
String token = await _storageService.getTokenAsync();
_storageService.setTokenAsync(entity.token);