How to navigate to another page but show information according to the items on my list that was pressed? - flutter

I'm trying to create my first app with flutter, it's a basic app to show items on a list and you tap on them to get the information. I've created the list and the contact page, I can navigate from one page to the other but I'm stuck now on how to make flutter show the information according to the contact I choose on the list, so I dont need to write one class for each contact. Is there a way to do it?
import 'package:flutter/material.dart';
import 'package:whatsapp_casimiro/contacts/contact_page.dart';
import 'package:whatsapp_casimiro/listas/lanchonetes.dart';
class LanchonetesScreen extends StatelessWidget {
final List<Lanchonetes> _allLanchonetes =
Lanchonetes.allLanchonetes();
#override
Widget build(BuildContext context) {
return Scaffold(body: getLanchonetesPageBody(context));
}
getLanchonetesPageBody(BuildContext context) {
return ListView.builder(
itemCount: _allLanchonetes.length,
itemBuilder: _getItemUI,
);
}
Widget _getItemUI(BuildContext context, index) {
return Column(children: <Widget>[
Padding(
padding: EdgeInsets.only(right: 20.0),
child: Divider(
color: Colors.black,
indent: 80.0,
height: 8.0,
),
),
ListTile(
contentPadding: EdgeInsets.fromLTRB(15.0, 10.0, 10.0, 10.0),
leading: Container(
width: 55.0,
height: 60.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
"images/" + _allLanchonetes[index].img)),
),
),
title: Text(
_allLanchonetes[index].name,
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
onTap: () {
_onLanchonetesButtonPressed(context);
},
)
]);
}
}
void _onLanchonetesButtonPressed(BuildContext context) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => ContactPage()));
}
class Lanchonetes {
final String name;
final String img;
Lanchonetes({this.name, this.img});
static List<Lanchonetes> allLanchonetes() {
var listOfLanchonetes = List<Lanchonetes>();
listOfLanchonetes.add(
Lanchonetes(name: "Esquina do Açaí",
img: "esquina_do_acai.jpg"));
listOfLanchonetes.add(
Lanchonetes(name: "Lanchonete Água na boca",
img: "esquina_do_acai.jpg"));
listOfLanchonetes.add(
Lanchonetes(name: "Kídelicia", img: "esquina_do_acai.jpg"));
listOfLanchonetes.add(
Lanchonetes(name: "Godinho Lanches", img: "godinho.jpeg" ));
return listOfLanchonetes;
}
}
import 'package:flutter/material.dart';
class ContactPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.blueGrey[100],
body: ListView(children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
child: Stack(children: <Widget>[
Image.asset("images/esquina_do_acai.jpg"),
Container(
height: 420.0,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: FractionalOffset.center,
end: FractionalOffset.bottomCenter,
colors: [
Colors.grey.withOpacity(0.0),
Colors.black,
])
),
),
Positioned(
bottom: 10.0,
left: 15.0,
child: Text(
"Esquina do Açaí",
style: TextStyle(
fontSize: 40.0,
fontWeight: FontWeight.normal,
color: Colors.white),
),
)
]
),
)
],
),
Padding(
padding: EdgeInsets.only(top: 5.0),
child: GestureDetector(
child: Card(
elevation: 1.0,
child: Container(
height: 100.0,
color: Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(
vertical: 30.0, horizontal: 15.0),
child: Text(
"Cardápio",
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold),
),
),
),
),
onTap: () {},
),
),
Card(
elevation: 1.0,
child: Container(
height: 100.0,
color: Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(
vertical: 30.0, horizontal: 15.0),
child: Text(
"Pedir",
style: TextStyle(
fontSize: 30.0, fontWeight:
FontWeight.bold),
),
)))
])));
}
}

In your Navigation function you can pass one object
on your onTap you should pass your object like this in navigation function
onTap: () {
_onLanchonetesButtonPressed(context, _allLanchonetes[index]);
}
and receive it at function and pass it to new page
void _onLanchonetesButtonPressed(BuildContext context,Lanchonetes lanchonetes) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => ContactPage(lanchonetes)));
}
on new page create constructor
class ContactPage extends StatelessWidget {
Lanchonetes lanchonetes;
ContactPage({this.lanchonetes});
//
Your code
//
}
with this you can use your lanchonetes object in new page

Related

ListView.builder returns Null check operator used on a null value

I'm developing a job search app that scrapes data from Indeed using Python which is being sent back to my Flutter UI as JSON data. The JSON data is being received successfully, however, Im getting an error of Null check operator used on a null value. The error appears to be stemming from the _jobSearch widget.
The relevant error-causing widget was ListView lib/ui/home_page.dart:256
Exception caught by scheduler library
Null check operator used on a null value
Here is the code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_job_portal/theme/colors.dart';
import 'package:flutter_job_portal/theme/images.dart';
import 'package:flutter_job_portal/ui/bottom_menu_bar.dart';
import 'package:flutter_job_portal/ui/job_detail_page.dart';
String job = ""; //user's response will be assigned to this variable
String final_response = "";
final _formkey = GlobalKey<FormState>(); //key created to interact with the form
//function to validate and save user form
Future<void> _savingData() async {
final validation = _formkey.currentState.validate();
if (!validation) {
return;
}
_formkey.currentState.save();
}
Future<List<Job>> _getJobs() async {
final url = 'http://127.0.0.1:5000/job';
final response1 = await http.post(Uri.parse(url), body: json.encode({'job': job}));
final response2 = await http.get(Uri.parse(url));
final decoded = json.decode(response2.body);
List<Job> jobs = [];
for (var i in decoded) {
Job job = Job(i['Title'], i['Company'], i['Location'], i['Salary']);
jobs.add(job);
}
return jobs;
}
class Job {
final String title;
final String company;
final String location;
final String salary;
Job(this.title, this.company, this.location, this.salary);
}
class HomePage extends StatelessWidget {
const HomePage({Key key}) : super(key: key);
Widget _appBar(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(
children: [
CircleAvatar(
backgroundImage: AssetImage(Images.user1),
),
Spacer(),
IconButton(
icon: Icon(Icons.notifications_none_rounded),
onPressed: () {},
)
],
),
);
}
Widget _header(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 12),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello, Alex!",
style: TextStyle(
fontSize: 15,
color: KColors.subtitle,
fontWeight: FontWeight.w500,
)),
SizedBox(
height: 6,
),
Text("Swipe to find your future",
style: TextStyle(
fontSize: 20,
color: KColors.title,
fontWeight: FontWeight.bold)),
SizedBox(
height: 10,
),
Row(
children: [
Expanded(
child: Container(
height: 45,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: KColors.lightGrey,
borderRadius: BorderRadius.circular(10)),
child: Form(
key: _formkey,
child: TextFormField(
decoration: InputDecoration(
hintText: 'Search job title or keywords',
),
onSaved: (value) {
job =
value; //getting data from the user form and assigning it to job
},
),
),
),
),
SizedBox(
width: 16,
),
Container(
decoration: BoxDecoration(
color: KColors.primary,
borderRadius: BorderRadius.circular(10),
),
height: 40,
child: IconButton(
color: KColors.primary,
icon: Icon(Icons.search, color: Colors.white),
onPressed: () async {
_savingData();
_getJobs();
},
),
)
],
)
],
),
);
}
Widget _recommendedSection(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
margin: EdgeInsets.symmetric(vertical: 12),
height: 200,
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Recommended",
style: TextStyle(fontWeight: FontWeight.bold, color: KColors.title),
),
SizedBox(height: 10),
Expanded(
child: ListView(
scrollDirection: Axis.horizontal,
children: [
_recommendedJob(context,
company: "Google",
img: Images.google,
title: "UX Designer",
sub: "\$45,000 Remote",
isActive: true),
_recommendedJob(context,
company: "DropBox",
img: Images.dropbox,
title: "Research Assist",
sub: "\$45,000 Remote",
isActive: false)
],
),
),
],
),
);
}
Widget _recommendedJob(
BuildContext context, {
String img,
String company,
String title,
String sub,
bool isActive = false,
}) {
return Padding(
padding: const EdgeInsets.only(right: 10),
child: GestureDetector(
onTap: () {
Navigator.push(context, JobDetailPage.getJobDetail());
},
child: AspectRatio(
aspectRatio: 1.3,
child: Container(
decoration: BoxDecoration(
color: isActive ? KColors.primary : Colors.white,
borderRadius: BorderRadius.circular(7),
),
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 40,
width: 40,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: isActive ? Colors.white : KColors.lightGrey,
borderRadius: BorderRadius.circular(7),
),
child: Image.asset(img),
),
SizedBox(height: 16),
Text(
company,
style: TextStyle(
fontSize: 12,
color: isActive ? Colors.white38 : KColors.subtitle,
),
),
SizedBox(height: 6),
Text(
title,
style: TextStyle(
fontSize: 14,
color: isActive ? Colors.white : KColors.title,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 6),
Text(
sub,
style: TextStyle(
fontSize: 12,
color: isActive ? Colors.white38 : KColors.subtitle,
),
),
],
),
),
),
),
);
}
Widget _jobSearch(BuildContext context) {
return new Container(
child: FutureBuilder(
future: _getJobs(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text('Loading...'),
));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index].location),
);
},
);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: KColors.background,
bottomNavigationBar: BottomMenuBar(),
body: SafeArea(
child: Container(
width: MediaQuery.of(context).size.width,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_appBar(context),
_header(context),
_recommendedSection(context),
_jobSearch(context)
],
),
),
),
),
);
}
}

passing data through the widget constructor

i am missing a small piece of information about constructors, i am trying to pass some data through the widget PromotionCard( [ ... ] ) i can't see any error in my debug console i tried Cards widgets and other different stuff to show the data but i can't find out what is wrong with this code down below.
Note: when i print snapshot.data i can see it perfectly returned
any help please.
**promotions_page.dart**
class PromotionsPage extends StatefulWidget {
#override
_PromotionsPageState createState() => _PromotionsPageState();
}
class _PromotionsPageState extends State<PromotionsPage> {
Future<Result> _promotionsResultsData;
#override
void initState() {
_promotionsResultsData = PromotionApi().fetchPromotions();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
child: ListView(
physics: PageScrollPhysics(),
children: [
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Акции',
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
fontFamily: 'BuffetBold',
),
),
InkWell(
onTap: () => print('Archive promotion pressed!'),
child: Text(
'Архив Акции',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
fontFamily: 'BuffetBold',
color: Colors.grey[400],
),
),
),
],
),
SizedBox(
height: 10.0,
),
Container(
child: FutureBuilder<Result>(
future: _promotionsResultsData,
builder: (context, snapshot) {
if (snapshot.hasData) {
return GridView.builder(
padding: EdgeInsets.zero,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
childAspectRatio: (45 / 35),
crossAxisCount: 1,
),
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: snapshot.data.result.length,
itemBuilder: (BuildContext context, int index) {
//print(snapshot.data.result.length);
var promos = snapshot.data.result[index];
PromotionCard(
id: promos.id,
title: promos.title,
description: promos.description,
image: promos.image);
},
);
} else {}
return Center(
child: Text(
"Loading ...",
style: TextStyle(
fontWeight: FontWeight.w900, fontSize: 30.0),
),
);
},
),
),
],
),
],
),
),
);
}
}
i am trying to pass data to this screen
**w_promotion_card.dart**
class PromotionCard extends StatelessWidget {
final String id;
final String title;
final String description;
final String image;
PromotionCard({this.id, this.title, this.description, this.image});
#override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: 200.0,
margin: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 10.0),
padding: EdgeInsets.zero,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(image),
alignment: Alignment.topCenter,
),
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
width: 1.5,
color: Colors.grey[300],
),
),
child: Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.zero,
child: Padding(
padding: EdgeInsets.fromLTRB(10, 170.0, 10.0, 10.0),
child: Text(
title,
style: TextStyle(
fontSize: 16.0,
fontFamily: 'BuffetRegular',
),
),
),
),
);
}
}
You missed the return statement
itemBuilder: (BuildContext context, int index) {
//print(snapshot.data.result.length);
var promos = snapshot.data.result[index];
// you have to return the widget
return PromotionCard(
id: promos.id,
title: promos.title,
description: promos.description,
image: promos.image);
},

How to add a plus Button in ListView Builder fetches the data from SQLite in Flutter

I have a ListView Builder where I have one Stateful Widget. I want to add a plus Button as Widget inside the ListView Item. What I am doing is that, I have added a number of records in SQLite when creating the database, and I have added a plus Icon and an empty as record/row to the database. So I am fetching the data from there. The Plus Button(Widget) is displaying as I expect but when update the data into the database the Button is not Showing at the Expected position, Because I want it to display at the end of all the items.
class CategoriesScreen extends StatefulWidget {
#override
_CategoriesScreenState createState() => _CategoriesScreenState();
}
class _CategoriesScreenState extends State<CategoriesScreen> {
List<Map<String,dynamic>> spendingCategoriesList=[] ;
DatabaseHelper helper=DatabaseHelper();
#override
Widget build(BuildContext context) {
getData();
return Scaffold(
backgroundColor: Color(0xFF343641),
body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height-100,
margin: EdgeInsets.only(top: 40.0),
child: Column(
children: <Widget>[
Container(
width:MediaQuery.of(context).size.width ,
height: 30.0,
margin: EdgeInsets.only(left: 20.0),
child: Row(
children: [
GestureDetector(
onTap:(){Navigator.pop(context);},
child: Icon(
Icons.close,
color: Color(0xFFE44663),
size: 24.0,
),
),
Padding(
padding: EdgeInsets.only(left:MediaQuery.of(context).size.width*0.3),
child: Text('Categories',style: TextStyle(color: Colors.white,fontWeight: FontWeight.normal,fontSize: 15.0,),),
),
],
),
),
Expanded(
child: GridView.builder(
itemCount: spendingCategoriesList.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemBuilder: (context,index){
AddTransactionsModel transactionModel= new AddTransactionsModel(spendingCategoriesList[index]['CategoryImage'],spendingCategoriesList[index]['categoryName']);
return AddTransactionItem(transactionModel);
}),
),
],
),
),
);
}
void getData() async{
spendingCategoriesList=await helper.getNoteMapList();
setState(() {
spendingCategoriesList=spendingCategoriesList;
});
}
Here is the AddTransactionGridItem;
class _AddTransactionItemState extends State<AddTransactionItem> {
var imageSelectIndex;
String categoryName;
String categoryImage;
#override
Widget build(BuildContext context) {
print(
'Hello dear ! icon Number ${widget.transactionModel.iconNumber} and here is Text ${widget.transactionModel.categoryNumber} ');
return Container(
child: Column(
children: <Widget>[
InkWell(
onTap: widget.transactionModel.categoryNumber == ''
? () {
showAddCategoryDialogue();
}
: () {
setState(() {
categoryName=widget.transactionModel.categoryNumber;
categoryImage=widget.transactionModel.iconNumber;
print('categoryName $categoryName And categoryImage $categoryImage');
String cate='$categoryName&$categoryImage';
Navigator.pop(context,cate);
});
},
child: Container(
width: 72.0,
height: 72.0,
decoration: BoxDecoration(
color: Color(0xffC4C4C4).withOpacity(0.2),
borderRadius: BorderRadius.all(Radius.circular(12.0)),
border: widget.transactionModel.categoryNumber == ''
? Border.all(width: 0.3, color: Colors.white)
: Border.all(width: 0.0),
),
child: Center(
child: Image.asset('${widget.transactionModel.iconNumber}')),
),
),
SizedBox(
height: 10.0,
),
Text(
widget.transactionModel.categoryNumber,
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.w600,
fontFamily: 'Rajdhani',
fontStyle: FontStyle.normal),
)
],
),
);
}
AboveContainer is the ListView.Builder() Item .

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)
),
),
)

adding ListView.builder

I'm trying to make the displayAccoutList() scrollable.
I've tried to use ListView but it didn't work. I'm thinking to use ListView.builder but I don't know how to create data for accountItems()
enter code here`import 'package:flutter/material.dart';
import 'app_drawer.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Accounts',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Account(),
);
}
}
class Account extends StatefulWidget {
#override
_AccountState createState() => _AccountState();
}
class _AccountState extends State<Account> {
Card topArea() =>
Card(
margin: EdgeInsets.all(10.0),
elevation: 1.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(50.0))),
child: Container(
decoration: BoxDecoration(
gradient: RadialGradient(
colors: [Color(0xFFFF5722), Color(0xFFFF5722)])),
padding: EdgeInsets.all(5.0),
// color: Color(0xFF015FFF),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.white,
),
onPressed: () {},
),
Text("Savings",
style: TextStyle(color: Colors.white, fontSize: 20.0)),
IconButton(
icon: Icon(
Icons.arrow_forward,
color: Colors.white,
),
onPressed: () {},
)
],
),
Center(
child: Padding(
padding: EdgeInsets.all(5.0),
child: Text(r"£ " "100,943.33",
style: TextStyle(color: Colors.white, fontSize: 24.0)),
),
),
SizedBox(height: 35.0),
],
)),
);
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: AppDrawer(),
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.grey, //change your color here
),
backgroundColor: Colors.white,
elevation: 0.0,
title: Text(
"Accounts",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.search,
color: Colors.grey,
),
onPressed: () {},
)
],
),
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
topArea(),
SizedBox(
height: 40.0,
child: Icon(Icons.refresh,
size: 35.0,
color: Color(0xFFFF5722),
),
),
displayAccoutList()
],
),
),
bottomNavigationBar: BottomAppBar(
elevation: 0.0,
child: Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
FlatButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 30.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
color: Color(0xFFFF5722),
// borderSide: BorderSide(color: Color(0xFF015FFF), width: 1.0),
onPressed: () {},
child: Text("ACTIVITY"),
),
OutlineButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 28.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
borderSide: BorderSide(color: Color(0xFFFF5722), width: 1.0),
onPressed: () {},
child: Text("STATEMENTS"),
),
OutlineButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 28.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
borderSide: BorderSide(color: Color(0xFFFF5722), width: 1.0),
onPressed: () {},
child: Text("DETAILS"),
)
],
),
),
)
);
}
}
Container accountItems(String item, String charge, String dateString,
String type,
{Color oddColour = Colors.white}) =>
Container(
decoration: BoxDecoration(color: oddColour),
padding:
EdgeInsets.only(top: 20.0, bottom: 20.0, left: 5.0, right: 5.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(item, style: TextStyle(fontSize: 16.0)),
Text(charge, style: TextStyle(fontSize: 16.0))
],
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(dateString,
style: TextStyle(color: Colors.grey, fontSize: 14.0)),
Text(type, style: TextStyle(color: Colors.grey, fontSize: 14.0))
],
),
],
),
);
displayAccoutList() {
return Container(
margin: EdgeInsets.all(15.0),
child: Column(
children: <Widget>[
accountItems("M KING", r"+ £ 4,946.00", "15-07-19", "Credit",
oddColour: const Color(0xFFF7F7F9)),
accountItems(
"Gordon Street Tenants", r"+ £ 5,428.00", "15-07-19", "Credit"),
accountItems("Amazon EU", r"+ £ 746.00", "15-07-19", "Credit",
oddColour: const Color(0xFFF7F7F9)),
accountItems(
"Floww LTD", r"+ £ 5,526.00", "15-07-19", "Credit"),
accountItems(
"KLM", r"- £ 2,500.00", "10-07-19", "Payment",
oddColour: const Color(0xFFF7F7F9)),
],
),
);
`
The other page app_drawer.dart
`
import 'package:flutter/material.dart';
class AppDrawer extends StatefulWidget {
#override
_AppDrawerState createState() => _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
#override
Widget build(BuildContext context) {
return SizedBox(
width: 160.0,
child: Drawer(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 50.0),
child: FlatButton.icon(
icon: Icon(
Icons.arrow_back,
color: Colors.grey,
),
onPressed: null,
label: Text("Back",
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 16.0,
color: Colors.black)),
color: Colors.black,
),
),
buildMenuItem(Icons.account_balance, "ACCOUNTS",
opacity: 1.0, color: Color(0xFFFF6E40)),
Divider(),
buildMenuItem(Icons.compare_arrows, "TRANSFER"),
Divider(),
buildMenuItem(Icons.receipt, "STATEMENTS"),
Divider(),
buildMenuItem(Icons.attach_money, "PAYMENTS"),
Divider(),
buildMenuItem(Icons.sentiment_satisfied, "INVESTMENTS"),
Divider(),
buildMenuItem(Icons.phone, "SUPPORT"),
Divider()
],
),
),
);
}
Opacity buildMenuItem(IconData icon, String title,
{double opacity = 0.3, Color color = Colors.black}) {
return Opacity(
opacity: opacity,
child: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 20.0,
),
Icon(
icon,
size: 50.0,
color: color,
),
SizedBox(
height: 10.0,
),
Text(title,
style: TextStyle(
fontWeight: FontWeight.w500, fontSize: 14.0, color: color)),
SizedBox(
height: 10.0,
),
],
),
),
);
}
}
`
To able to scroll through the section and have unlimited amount of transaction
I think this is what you are going for.
In this snippet, I defined Language as a class with attributes language and rating.
Then I created a list of languages in the stateless widget TheList.
Finally, I used the listView.builder to map the list for its length and display text that shows the attributes of the languages.
Let me know if you have any questions!
import 'package:flutter/material.dart';
class Language {
const Language({this.language,this.rating});
final String language;
final String rating;
}
class TheList extends StatelessWidget {
// Builder methods rely on a set of data, such as a list.
final List<Language> _languages = [
const Language(language: "flutter", rating: "amazing"),
const Language(language: "javascript", rating: "stellar"),
const Language(language: "java", rating: "sucks"),
];
// First, make your build method like normal.
// Instead of returning Widgets, return a method that returns widgets.
// Don't forget to pass in the context!
#override
Widget build(BuildContext context) {
return _buildList(context);
}
// A builder method almost always returns a ListView.
// A ListView is a widget similar to Column or Row.
// It knows whether it needs to be scrollable or not.
// It has a constructor called builder, which it knows will
// work with a List.
ListView _buildList(context) {
return ListView.builder(
// Must have an item count equal to the number of items!
itemCount: _languages.length,
// A callback that will return a widget.
itemBuilder: (context, index) {
// In our case, a Language and its rating for each language in the list.
return Text(_languages[index].language + ": " + _languages[index].rating);
},
);
}
}