Why my value is not updating in GetX Flutter - android

I made two very simple pages in GetX for learning it. I created three variabes for it, one is counter and other is destination and departure cities. The counter variable is updating perfectly, while the other variables are not changing their values. They only change when I hot reload.
If you think I have missed something or this doubt is very common and you have seen a very similar example like mine, please share it's link or correct the code if you can.
Here is my class:
import 'package:get/get.dart';
class Controller extends GetxController {
var count = 0.obs;
var des = "Delhi".obs;
var dep = "Agra".obs;
void increment() {
count.value++;
update();
}
void updateDes(String input) {
des = input.obs;
}
void updateDep(String input) {
dep = input.obs;
}
}
Here is the first Page (you may check out lines 14, 30-52) -
import 'package:flutter/material.dart';
import 'package:flutter_application_firebase_noti_basics/my_controller.dart';
import 'package:flutter_application_firebase_noti_basics/new_home.dart';
import 'package:get/get.dart';
class Sample extends StatefulWidget {
const Sample({Key? key}) : super(key: key);
#override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
final my_controller = Get.put(Controller());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Container(
width: 300,
height: 300,
color: Colors.grey[400],
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Obx(
() => InkWell(
child: Text("${my_controller.des}"),
onTap: () {
Get.to(NewHome(
num: 1,
));
},
),
),
const SizedBox(
height: 20,
),
Obx(
() => InkWell(
child: Text('${my_controller.dep}'),
onTap: () {
Get.to(NewHome(
num: 2,
));
},
),
),
],
),
),
),
),
);
}
}
Here is the city selection page (you may want to check out lines: 32, 93-103, 121-125)-
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'my_controller.dart';
class NewHome extends StatefulWidget {
int? num = 0;
NewHome({
Key? key,
this.num,
}) : super(key: key);
#override
_NewHomeState createState() => _NewHomeState();
}
class _NewHomeState extends State<NewHome> {
final List<Map<String, dynamic>> _allCities = [
{"id": 1, "city": "Delhi", "state": ""},
{"id": 2, "city": "Agra", "state": "UP"},
{"id": 3, "city": "Mumbai", "state": "Maharashtra"},
{"id": 4, "city": "Jaipur", "state": "Rajasthan"},
{"id": 5, "city": "Jodhpur", "state": "Rajasthan"},
{"id": 6, "city": "Ranchi", "state": "Jharkhand"},
{"id": 7, "city": "Dhanbad", "state": "Jharkhand"},
{"id": 8, "city": "Kanpur", "state": "UP"},
{"id": 9, "city": "Chandigarh", "state": "Punjab"},
{"id": 10, "city": "Meerut", "state": "UP"},
];
final controller = Get.put(Controller());
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: const Color(0xffEEEDEF),
body: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back),
color: Colors.orange,
onPressed: () {
Navigator.pop(context);
},
),
Container(
width: MediaQuery.of(context).size.width * 0.85,
height: 50.0,
decoration: BoxDecoration(
color: Colors.white,
borderRadius:
const BorderRadius.all(Radius.circular(5.0)),
border: Border.all(color: Colors.blueAccent)),
child: TextField(
decoration: InputDecoration(
hintText: "Enter Origin",
border: InputBorder.none,
contentPadding: const EdgeInsets.only(left: 10.0),
hintStyle: TextStyle(
fontSize: 15.0,
color: Colors.grey[500],
),
),
),
),
],
),
),
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.width * 0.04, top: 3.0),
child: Text(
'Popular Searches:',
style: TextStyle(
color: Colors.grey[500],
fontSize: MediaQuery.of(context).size.width * 0.035),
),
),
),
Expanded(
child: ListView.builder(
itemCount: _allCities.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
controller.increment();
if (widget.num == 1) {
controller.updateDes(_allCities[index]['city']);
Get.back();
} else if (widget.num == 2) {
controller.updateDep(_allCities[index]['city']);
Get.back();
} else {
Get.back();
}
},
child: Padding(
padding: const EdgeInsets.only(
left: 18.0, top: 10.0, bottom: 15.0),
child: Text(
_allCities[index]['city'],
style: const TextStyle(
color: Colors.black,
fontSize: 15.0,
fontWeight: FontWeight.normal,
),
),
),
);
},
),
),
Obx(
() => Text("${controller.count} cities are selected",
style: const TextStyle(fontSize: 20.0)),
)
],
),
),
);
}
}

That's because you're not updating the values properly. When using reactive (obs) variables, you're expected to update the value property of the variable.
Also you should not use update with obs variables as they will be automatically updated. So your controller will be:
class Controller extends GetxController {
var count = 0.obs;
var des = "Delhi".obs;
var dep = "Agra".obs;
void increment() {
count.value++;
// removed update()
}
void updateDes(String input) {
// changing from des = input.obs
des.value = input;
}
void updateDep(String input) {
// changing from dep = input.obs
dep.value = input;
}
}

You need to remove update from your code and .obs from string value like this:
import 'package:get/get.dart';
class Controller extends GetxController {
var count = 0.obs;
var des = "Delhi".obs;
var dep = "Agra".obs;
void increment() {
count.value++;
// remove this ---> update();
}
void updateDes(String input) {
des=input
// remove this---> des = input.obs;
}
void updateDep(String input) {
// remove this---> dep = input.obs;
dep=input
}
}

import 'package:get/get.dart';
class Controller extends GetxController {
var count = 0.obs;
var des = "Delhi".obs;
var dep = "Agra".obs;
void increment() {
count.value++;
}
void updateDes(String input) {
des = input.obs;
}
void updateDep(String input) {
dep = input.obs;
}
}
In your first page code you need to remove updated() function because if you are using obs then no need to use update().
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'my_controller.dart';
class NewHome extends StatefulWidget {
int? num = 0;
NewHome({
Key? key,
this.num,
}) : super(key: key);
#override
_NewHomeState createState() => _NewHomeState();
}
class _NewHomeState extends State<NewHome> {
final List<Map<String, dynamic>> _allCities = [
{"id": 1, "city": "Delhi", "state": ""},
{"id": 2, "city": "Agra", "state": "UP"},
{"id": 3, "city": "Mumbai", "state": "Maharashtra"},
{"id": 4, "city": "Jaipur", "state": "Rajasthan"},
{"id": 5, "city": "Jodhpur", "state": "Rajasthan"},
{"id": 6, "city": "Ranchi", "state": "Jharkhand"},
{"id": 7, "city": "Dhanbad", "state": "Jharkhand"},
{"id": 8, "city": "Kanpur", "state": "UP"},
{"id": 9, "city": "Chandigarh", "state": "Punjab"},
{"id": 10, "city": "Meerut", "state": "UP"},
];
#override
Widget build(BuildContext context) {
Get.lazyPut(() => Controller());// this line you need to add in your second file
return SafeArea(
child: Scaffold(
backgroundColor: const Color(0xffEEEDEF),
body: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back),
color: Colors.orange,
onPressed: () {
Navigator.pop(context);
},
),
Container(
width: MediaQuery.of(context).size.width * 0.85,
height: 50.0,
decoration: BoxDecoration(
color: Colors.white,
borderRadius:
const BorderRadius.all(Radius.circular(5.0)),
border: Border.all(color: Colors.blueAccent)),
child: TextField(
decoration: InputDecoration(
hintText: "Enter Origin",
border: InputBorder.none,
contentPadding: const EdgeInsets.only(left: 10.0),
hintStyle: TextStyle(
fontSize: 15.0,
color: Colors.grey[500],
),
),
),
),
],
),
),
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.width * 0.04, top: 3.0),
child: Text(
'Popular Searches:',
style: TextStyle(
color: Colors.grey[500],
fontSize: MediaQuery.of(context).size.width * 0.035),
),
),
),
Expanded(
child: ListView.builder(
itemCount: _allCities.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
controller.increment();
if (widget.num == 1) {
controller.updateDes(_allCities[index]['city']);
Get.back();
} else if (widget.num == 2) {
controller.updateDep(_allCities[index]['city']);
Get.back();
} else {
Get.back();
}
},
child: Padding(
padding: const EdgeInsets.only(
left: 18.0, top: 10.0, bottom: 15.0),
child: Text(
_allCities[index]['city'],
style: const TextStyle(
color: Colors.black,
fontSize: 15.0,
fontWeight: FontWeight.normal,
),
),
),
);
},
),
),
Obx(
() => Text("${controller.count.value} cities are selected",
style: const TextStyle(fontSize: 20.0)),
)
],
),
),
);
}
}
Kindly check this second page code i did some correction now may it will work fine.
Now in third page according to the second page you can change.
Main Thing about Get-X Statemanagment:-
If you are using obx then no need to use update() function.
when you'll access any member variable's value then you need to use .value. like controller.count.value.
You need to add this line in any screen where you want to use GetX controller class:- Get.lazyPut(() => Controller()); this line will be add before Scaffold return statement.
Wrap with Obx() only that widget in which you want to add observation.

Related

GridView in Flutter

I'm working on a flutter project and I made a GridView with images and titles but I want the title to be outside the square, If I make padding they give this error BOTTOM OVERFLOWED BY 32 PIXELS. Any help is highly appreciated.
this is my code :
Card makeDashboardItem(String title, String img, int index) {
return Card(
elevation: 2,
margin: const EdgeInsets.all(3),
child: Container(
child: InkWell(
onTap: () {
setState(() {
isLoading = true;
});
_splitScreen2(index);
},
child: Column(
children: <Widget>[
const SizedBox(height: 10),
Center(
child: Image.asset(img,
alignment: Alignment.center),
),
const SizedBox(height: 1),
Center(
child: Text(
title,
style: const TextStyle(
fontSize: 13,
color: Colors.black,
),
),
),
],
),
),
),
);
}
Check DartPad
The Main problem was overflow so we wrap Expanded widget on Image widget.
Nb: Remove Expanded widget from Image widget You can see the difference
CardWidget
class ItemWidget extends StatelessWidget {
var data;
ItemWidget(this.data, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 150,
child: Card(
child: Column(
children: [
Expanded(
child: Container(
height: 125,
child: Image.network(
data["Image"],
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
Center(
child: Text(
data["Name"],
style: TextStyle(fontSize: 12),
))
],
),
),
);
}
}
Fullcode
import 'package:flutter/material.dart';
runApp(
MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
var list = [
{
"Name": "ElectroniQues",
"Image":
"https://ecommerce.ccc2020.fr/wp-content/uploads/2020/10/electronic-gadgets.jpeg"
},
{
"Name": "Accessories",
"Image":
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/classic-accessories-1516305397.jpg"
},
{
"Name": "Hommes",
"Image":
"https://teja12.kuikr.com/is/a/c/880x425/gallery_images/original/cf5d08bff955e71.gif"
},
{
"Name": "Femmes",
"Image":
"https://cdn.pixabay.com/photo/2013/07/13/14/08/apparel-162192_1280.png"
},
{
"Name": "Enfants",
"Image": "https://images.indianexpress.com/2019/09/toys.jpg"
},
{
"Name": "Sunglasses",
"Image": "https://m.media-amazon.com/images/I/51zEsraniRL._UX569_.jpg"
},
{
"Name": "ElectroniQues",
"Image":
"https://ecommerce.ccc2020.fr/wp-content/uploads/2020/10/electronic-gadgets.jpeg"
},
{
"Name": "Accessories",
"Image":
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/classic-accessories-1516305397.jpg"
},
{
"Name": "Hommes",
"Image":
"https://teja12.kuikr.com/is/a/c/880x425/gallery_images/original/cf5d08bff955e71.gif"
},
{
"Name": "Femmes",
"Image":
"https://cdn.pixabay.com/photo/2013/07/13/14/08/apparel-162192_1280.png"
},
{
"Name": "Enfants",
"Image": "https://images.indianexpress.com/2019/09/toys.jpg"
},
{
"Name": "Sunglasses",
"Image": "https://m.media-amazon.com/images/I/51zEsraniRL._UX569_.jpg"
},
];
var column = Column(mainAxisAlignment: MainAxisAlignment.start, children: [
...list.map((e) {
return GestureDetector(onTap:(){},child: ItemWidget(e));
}).toList()
]);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Row(
children: [
SideWidget(),
Expanded(
child: Scaffold(
bottomNavigationBar: buildBottomNavigationBar(),
body: Padding(
padding: const EdgeInsets.only(top: 18.0),
child:
// column
GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 2,
crossAxisSpacing: 2,
children: [
...list.map((e) {
return InkWell(onTap:(){},child: ItemWidget(e));
}).toList()
],
),
),
),
),
],
),
),
);
}
BottomNavigationBar buildBottomNavigationBar() {
return BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: 0,
selectedItemColor: Colors.amber[800],
onTap: (v) {},
);
}
}
class SideWidget extends StatelessWidget {
const SideWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
child: Container(
width: 63,
color: Colors.white,
child: ListView(
children: [
...[
Icons.headset,
Icons.pets,
Icons.watch,
Icons.color_lens,
Icons.today
]
.map((e) => Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 4.0),
child: TextButton(
onPressed: () {},
child: Icon(
e,
color: Colors.blueGrey,
size: 40,
),
),
))
.toList()
],
),
),
);
}
}
class ItemWidget extends StatelessWidget {
var data;
ItemWidget(this.data, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 150,
child: Card(
child: Column(
children: [
Expanded(
child: Container(
height: 125,
child: GridTile(
// footer:Text(data["Name"]) ,
child: Image.network(
data["Image"],
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
),
Center(
child: Text(
data["Name"],
style: TextStyle(fontSize: 12),
))
],
),
),
);
}
}
GridView children size depends on aspect ratio, which is 1 by default. In your case, image is not getting proper height.
For your case, You can use fit on Image.asset.
Image.asset(
"",
fit: BoxFit.cover, // or the .width or the one you prefer
),
Also you can try GridTile
GridTile(
child: Image.asset(
"",
fit: BoxFit.cover,
),
footer: Text("title"),
),
More about GridTile and BoxFit.
Firstly, the way you have created the widget tree is not proper.
Currently, you have
Card -> Container -> Column -> 1. Image
2. Text
If you want the title to be out of your square (Card), it should be:
Column -> 1. Card -> Image
2. Text
This way your title will be out of the card.

How to get all events in a month using table_calendar in flutter?

I have built a calendar with user's appointments using table_calendar in flutter. In my current code, I can only return all appointments of the user. Now, I am trying to fetch all appointments within a same month only and display them below the calendar. That is to say, when I swap the month on the calendar, I should only see a list of appointments within the month I am currently looking at.
Currently, I am fetching all appointment records of the user from backend. To achieve my goal, which way will be easier:
by defining the 'change month button' with date info of the first day of that month and using it to select corresponding data in backend
OR
still retrieving all appointment records and filter them in frontend somehow?
Can anyone please help me achieving my goal with specific solution?
(As shown in my current output below, while I am at October, I am still seeing the appointment in June).
Current Output
Frontend code:
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:frontend/util/authentication.dart';
import 'package:frontend/util/serverDetails.dart';
import 'package:http/http.dart' as http;
import 'package:frontend/components/appointment.dart';
import 'package:frontend/screens/appointmentdetail.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:frontend/main.dart';
import 'package:frontend/screens/appointmentlist.dart';
class Appointments extends StatefulWidget {
#override
_AppointmentsState createState() => _AppointmentsState();
}
class _AppointmentsState extends State<Appointments>
with TickerProviderStateMixin {
var _calendarController;
Map<DateTime, List> _events;
List<Appointment> _samemonthevents = List<Appointment>();
AnimationController _animationController;
#override
void initState() {
super.initState();
_events = Map<DateTime, List>();
_calendarController = CalendarController();
getSameMonthAppointments();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}
#override
void dispose() {
_calendarController.dispose();
super.dispose();
}
getSameMonthAppointments() async {
String currentToken = await Authentication.getCurrentToken();
print(currentToken);
if (currentToken == null) {
print('bouncing');
Authentication.bounceUser(context);
} else {
String auth = "Bearer " + currentToken;
String url = ServerDetails.ip +
':' +
ServerDetails.port +
ServerDetails.api +
'me/appointments';
print(url);
Map<String, String> headers = {"Authorization": auth};
print(headers);
var jsonResponse = null;
var response = await http.get(url, headers: headers);
print(response.body);
if (response.statusCode == 200) {
print("200" + response.body);
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
setState(() {
for (var doc in jsonResponse) {
_samemonthevents.add(Appointment.fromJson(doc));
}
});
}
} else {
print(response.body);
}
}
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(60.0),
child: AppBar(
leading: new IconButton(
icon: new Icon(Icons.arrow_back),
color: Colors.black,
onPressed: () {
setState(() {});
Navigator.push(context,
MaterialPageRoute(builder: (context) => MainPage()));
}),
centerTitle: true,
title: Text("Appointment", style: TextStyle(color: Colors.black)),
backgroundColor: Colors.white,
brightness: Brightness.light,
automaticallyImplyLeading: false,
// backgroundColor: Color(0x44000000),
elevation: 0.5,
actions: <Widget>[
IconButton(
color: Colors.black,
icon: Icon(Icons.list),
onPressed: () {
setState(() {});
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AppointmentList()));
},
)
],
),
),
body: new Builder(builder: (BuildContext context) {
return new Column(children: <Widget>[
_buildTableCalendarWithBuilders(),
const SizedBox(height: 8.0),
const SizedBox(height: 8.0),
//_buildEventList()
//_buildsameMonthEventList()
Expanded(child: _buildsameMonthEventList()),
]);
}));
}
// More advanced TableCalendar configuration (using Builders & Styles)
Widget _buildTableCalendarWithBuilders() {
return TableCalendar(
calendarController: _calendarController,
events: _events,
//holidays: _holidays,
initialCalendarFormat: CalendarFormat.month,
formatAnimation: FormatAnimation.slide,
startingDayOfWeek: StartingDayOfWeek.sunday,
availableGestures: AvailableGestures.all,
availableCalendarFormats: const {CalendarFormat.month: ''},
calendarStyle: CalendarStyle(
outsideDaysVisible: false,
weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
),
daysOfWeekStyle: DaysOfWeekStyle(
weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonVisible: false,
),
builders: CalendarBuilders(
selectedDayBuilder: (context, date, _) {
return FadeTransition(
opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
child: Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blue[300],
borderRadius: BorderRadius.circular(36.0),
border: Border.all(width: 2, color: Colors.blue[300])),
child: Text(
'${date.day}',
style: TextStyle().copyWith(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold),
),
),
);
},
todayDayBuilder: (context, date, _) {
return Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(36.0),
border: Border.all(width: 2, color: Colors.white)),
child: Text(
'${date.day}',
style: TextStyle().copyWith(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold),
),
);
},
markersBuilder: (context, date, events, holidays) {
final children = <Widget>[];
if (events.isNotEmpty) {
children.add(
Positioned(
child: _buildEventsMarker(date, events),
),
);
}
if (holidays.isNotEmpty) {
children.add(
Positioned(
right: -2,
top: -2,
child: _buildHolidaysMarker(),
),
);
}
return children;
},
),
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
Widget _buildEventsMarker(DateTime date, List events) {
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(36.0),
border: Border.all(width: 2, color: Colors.blue[300])),
);
}
Widget _buildHolidaysMarker() {
return Icon(
Icons.add_box,
size: 20.0,
color: Colors.blueGrey[800],
);
}
Widget _buildsameMonthEventList() {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(22.0),
child: AppBar(
centerTitle: true,
title: Text("Appointments of Current Month",
style: TextStyle(color: Colors.black, fontSize: 18)),
backgroundColor: Colors.yellow[200],
brightness: Brightness.light,
automaticallyImplyLeading: false,
// backgroundColor: Color(0x44000000),
elevation: 0.5,
),
),
body: (_samemonthevents.length == 0)
? Text("No appointment record in current month!",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 16))
: ListView(
children: _samemonthevents
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 4.0),
child: (event is Appointment)
? ListTile(
leading: Column(children: <Widget>[
//Show Weekday, Month and day of Appiontment
Text(
DateFormat('EE').format(event.date) +
' ' +
DateFormat.MMMd().format(event.date),
style: TextStyle(
color: Colors.blue.withOpacity(1.0),
fontWeight: FontWeight.bold,
)),
//Show Start Time of Appointment
Text(DateFormat.jm().format(event.date),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.bold,
height: 1.5,
)),
//Show End Time of Appointment
Text(
DateFormat.jm().format(event.date.add(
Duration(
minutes: event.duration ?? 0))),
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
]), //Text(DateFormat.Hm().format(event.date)),//DateFormat.Hm().format(now)
title: Text(event.title),
trailing: event.status == 'UNCONFIRMED'
? Column(children: <Widget>[
//event.status=='CONFIRMED' ?
Icon(Icons.error,
color: Colors.pink,
//size:25.0,
semanticLabel:
'Unconfirmed Appointment'), //:Container(width:0,height:0),
Icon(Icons.arrow_right),
])
: Icon(Icons.arrow_right),
onTap: () {
setState(() {});
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AppointmentDetail(event)));
},
)
: null))
.toList()));
}
}
Backend Code:
AppointmentAPI.java
#GET
#Path("me/appointments")
#Secured(UserRole.PATIENT)
#JSONP(queryParam = "callback")
#Produces(MediaType.APPLICATION_JSON)
public Response listMyAppointments(
#Context SecurityContext sc,
#QueryParam("since") String since,
#QueryParam("until") String until,
#QueryParam("is_confirmed") Boolean is_confirmed) {
String uid = sc.getUserPrincipal().getName();
List<Appointment> results = retrieveUserAppointments(uid, since, until, is_confirmed);
return Response.ok(results).build();
}
AppointmentMapper.java
List<Appointment> getAppointmentsByUserId(
#Param("uid") String uid,
#Param("since") String since,
#Param("until") String until,
#Param("status") AppointmentStatus status);
AppointmentMapper.xml
<mapper namespace="com.sec.db.AppointmentMapper">
<select id="getAppointmentById" parameterType="String" resultType="com.sec.entity.Appointment">
SELECT * FROM Appointment WHERE id= #{id}
</select>
<select id="getAppointmentsByUserId" resultType="com.sec.entity.Appointment">
SELECT *
FROM Appointment
WHERE uid= #{uid}
<choose>
<when test="since != null and until != null">
AND date BETWEEN #{since} AND #{until}
</when>
<when test="since != null and until == null">
AND date > #{since}
</when>
<when test="since == null and until != null">
<![CDATA[
AND date < #{until}
]]>
</when>
</choose>
<choose>
<when test="status == null">
AND status != 'CANCELLED'
</when>
<otherwise>
AND status = #{status}
</otherwise>
</choose>
</select>
Json Response Example:
### Response
Status: 200 OK
```JSON
[
{
"date": "2020-06-22T14:15:00Z",
"date_change": "2018-05-14T10:17:40Z",
"date_create": "2018-05-14T10:17:40Z",
"detail": "Inflisaport Insertion",
"duration": 15,
"id": "2",
"note": "Looking forward to see you! Take care",
"status": "CONFIRMED",
"title": "Private Hospital",
"uid": "1"
}
]
You can copy paste run full code below
Step 1: You can use a variable current to control current year/month
Step 2: You can in _onVisibleDaysChanged, call setState and set current
Step 3: In _buildsameMonthEventList, do filter with every events year/month with current's year/month
code snippet
DateTime current = DateTime.now();
...
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
setState(() {
current = first;
});
print('CALLBACK: _onVisibleDaysChanged first ${first.toIso8601String()}');
}
...
Widget _buildsameMonthEventList() {
var _samemontheventsFilter = _samemonthevents.where((element) =>
element.date.year == current.year &&
element.date.month == current.month);
return Scaffold(
...
body: (_samemontheventsFilter.length == 0)
? Text("No appointment record in current month!",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 16))
: ListView(
children: _samemontheventsFilter
.map((event) => Container(
working demo
full code
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:intl/intl.dart';
List<Appointment> appointmentFromJson(String str) => List<Appointment>.from(
json.decode(str).map((x) => Appointment.fromJson(x)));
String appointmentToJson(List<Appointment> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Appointment {
Appointment({
this.date,
this.dateChange,
this.dateCreate,
this.detail,
this.duration,
this.id,
this.note,
this.status,
this.title,
this.uid,
});
DateTime date;
DateTime dateChange;
DateTime dateCreate;
String detail;
int duration;
String id;
String note;
String status;
String title;
String uid;
factory Appointment.fromJson(Map<String, dynamic> json) => Appointment(
date: DateTime.parse(json["date"]),
dateChange: DateTime.parse(json["date_change"]),
dateCreate: DateTime.parse(json["date_create"]),
detail: json["detail"],
duration: json["duration"],
id: json["id"],
note: json["note"],
status: json["status"],
title: json["title"],
uid: json["uid"],
);
Map<String, dynamic> toJson() => {
"date": date.toIso8601String(),
"date_change": dateChange.toIso8601String(),
"date_create": dateCreate.toIso8601String(),
"detail": detail,
"duration": duration,
"id": id,
"note": note,
"status": status,
"title": title,
"uid": uid,
};
}
class Appointments extends StatefulWidget {
#override
_AppointmentsState createState() => _AppointmentsState();
}
class _AppointmentsState extends State<Appointments>
with TickerProviderStateMixin {
var _calendarController;
Map<DateTime, List> _events;
List<Appointment> _samemonthevents = List<Appointment>();
AnimationController _animationController;
DateTime current = DateTime.now();
#override
void initState() {
super.initState();
_events = Map<DateTime, List>();
_calendarController = CalendarController();
getSameMonthAppointments();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}
#override
void dispose() {
_calendarController.dispose();
super.dispose();
}
getSameMonthAppointments() async {
String jsonString = '''
[
{
"date": "2020-09-01T11:15:00Z",
"date_change": "2018-05-14T10:17:40Z",
"date_create": "2018-05-14T10:17:40Z",
"detail": "Inflisaport Insertion",
"duration": 15,
"id": "2",
"note": "Looking forward to see you! Take care",
"status": "CONFIRMED",
"title": "Private Hospital",
"uid": "1"
},
{
"date": "2020-09-22T01:15:00Z",
"date_change": "2018-05-14T10:17:40Z",
"date_create": "2018-05-14T10:17:40Z",
"detail": "Inflisaport Insertion",
"duration": 15,
"id": "2",
"note": "Looking forward to see you! Take care",
"status": "CONFIRMED",
"title": "Private Hospital",
"uid": "1"
},
{
"date": "2020-10-01T07:15:00Z",
"date_change": "2018-05-14T10:17:40Z",
"date_create": "2018-05-14T10:17:40Z",
"detail": "Inflisaport Insertion",
"duration": 15,
"id": "2",
"note": "Looking forward to see you! Take care",
"status": "CONFIRMED",
"title": "Private Hospital",
"uid": "1"
},
{
"date": "2020-10-22T09:15:00Z",
"date_change": "2018-05-14T10:17:40Z",
"date_create": "2018-05-14T10:17:40Z",
"detail": "Inflisaport Insertion",
"duration": 15,
"id": "2",
"note": "Looking forward to see you! Take care",
"status": "CONFIRMED",
"title": "Private Hospital",
"uid": "1"
},
{
"date": "2020-10-30T10:15:00Z",
"date_change": "2018-05-14T10:17:40Z",
"date_create": "2018-05-14T10:17:40Z",
"detail": "Inflisaport Insertion",
"duration": 15,
"id": "2",
"note": "Looking forward to see you! Take care",
"status": "CONFIRMED",
"title": "Private Hospital",
"uid": "1"
}
]
''';
http.Response response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
_samemonthevents = appointmentFromJson(response.body);
}
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
setState(() {
current = first;
});
print('CALLBACK: _onVisibleDaysChanged first ${first.toIso8601String()}');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(60.0),
child: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.black,
onPressed: () {
setState(() {});
/* Navigator.push(context,
MaterialPageRoute(builder: (context) => MainPage()));*/
}),
centerTitle: true,
title: Text("Appointment", style: TextStyle(color: Colors.black)),
backgroundColor: Colors.white,
brightness: Brightness.light,
automaticallyImplyLeading: false,
// backgroundColor: Color(0x44000000),
elevation: 0.5,
actions: <Widget>[
IconButton(
color: Colors.black,
icon: Icon(Icons.list),
onPressed: () {
setState(() {});
/* Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AppointmentList()));*/
},
)
],
),
),
body: Builder(builder: (BuildContext context) {
return Column(children: <Widget>[
_buildTableCalendarWithBuilders(),
const SizedBox(height: 8.0),
const SizedBox(height: 8.0),
//_buildEventList()
//_buildsameMonthEventList()
Expanded(child: _buildsameMonthEventList()),
]);
}));
}
// More advanced TableCalendar configuration (using Builders & Styles)
Widget _buildTableCalendarWithBuilders() {
return TableCalendar(
calendarController: _calendarController,
events: _events,
//holidays: _holidays,
initialCalendarFormat: CalendarFormat.month,
formatAnimation: FormatAnimation.slide,
startingDayOfWeek: StartingDayOfWeek.sunday,
availableGestures: AvailableGestures.all,
availableCalendarFormats: const {CalendarFormat.month: ''},
calendarStyle: CalendarStyle(
outsideDaysVisible: false,
weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
),
daysOfWeekStyle: DaysOfWeekStyle(
weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonVisible: false,
),
builders: CalendarBuilders(
selectedDayBuilder: (context, date, _) {
return FadeTransition(
opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
child: Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blue[300],
borderRadius: BorderRadius.circular(36.0),
border: Border.all(width: 2, color: Colors.blue[300])),
child: Text(
'${date.day}',
style: TextStyle().copyWith(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold),
),
),
);
},
todayDayBuilder: (context, date, _) {
return Container(
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(36.0),
border: Border.all(width: 2, color: Colors.white)),
child: Text(
'${date.day}',
style: TextStyle().copyWith(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold),
),
);
},
markersBuilder: (context, date, events, holidays) {
final children = <Widget>[];
if (events.isNotEmpty) {
children.add(
Positioned(
child: _buildEventsMarker(date, events),
),
);
}
if (holidays.isNotEmpty) {
children.add(
Positioned(
right: -2,
top: -2,
child: _buildHolidaysMarker(),
),
);
}
return children;
},
),
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
Widget _buildEventsMarker(DateTime date, List events) {
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(4.0),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(36.0),
border: Border.all(width: 2, color: Colors.blue[300])),
);
}
Widget _buildHolidaysMarker() {
return Icon(
Icons.add_box,
size: 20.0,
color: Colors.blueGrey[800],
);
}
Widget _buildsameMonthEventList() {
var _samemontheventsFilter = _samemonthevents.where((element) =>
element.date.year == current.year &&
element.date.month == current.month);
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(22.0),
child: AppBar(
centerTitle: true,
title: Text("Appointments of Current Month",
style: TextStyle(color: Colors.black, fontSize: 18)),
backgroundColor: Colors.yellow[200],
brightness: Brightness.light,
automaticallyImplyLeading: false,
// backgroundColor: Color(0x44000000),
elevation: 0.5,
),
),
body: (_samemontheventsFilter.length == 0)
? Text("No appointment record in current month!",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 16))
: ListView(
children: _samemontheventsFilter
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 4.0),
child: (event is Appointment)
? ListTile(
leading: SizedBox(
width: 90,
child: Column(children: <Widget>[
//Show Weekday, Month and day of Appiontment
Text(
DateFormat('EE').format(event.date) +
' ' +
DateFormat.MMMd().format(event.date),
style: TextStyle(
color: Colors.blue.withOpacity(1.0),
fontWeight: FontWeight.bold,
)),
//Show Start Time of Appointment
Text(DateFormat.jm().format(event.date),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.bold,
height: 1.5,
)),
//Show End Time of Appointment
Text(
DateFormat.jm().format(event.date.add(
Duration(
minutes: event.duration ?? 0))),
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
]),
), //Text(DateFormat.Hm().format(event.date)),//DateFormat.Hm().format(now)
title: Text(event.title),
trailing: event.status == 'UNCONFIRMED'
? Column(children: <Widget>[
//event.status=='CONFIRMED' ?
Icon(Icons.error,
color: Colors.pink,
//size:25.0,
semanticLabel:
'Unconfirmed Appointment'), //:Container(width:0,height:0),
Icon(Icons.arrow_right),
])
: Icon(Icons.arrow_right),
onTap: () {
setState(() {});
/* Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AppointmentDetail(event)));*/
},
)
: null))
.toList()));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Appointments(),
);
}
}

User Entered Data is not saved on Firebase_realtime_database

User Entered Data is not saved on Firebase_realtime_database.I tried making a personal information form . But when I click on submit button , the data entred by user is not saving in firebase(real-time database). What could be error?
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';
import 'package:firebase_database/firebase_database.dart';
class DonorRegistration extends StatefulWidget {
#override
DonorRegistration({Key key}) : super(key: key);
#override
_DonorRegistrationState createState() => _DonorRegistrationState();
}
}
class _DonorRegistrationState extends State<DonorRegistration> {
var data;
bool autoValidate = true;
bool readOnly = false;
bool showSegmentedControl = true;
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
final ValueChanged _onChanged = (val) => print(val);
var currentItemSelected3;
bool disabledropdown = true;
final TextEditingController _nameController = TextEditingController();
String _gender = 'Male';
final TextEditingController _ageController = TextEditingController();
final dbRef = FirebaseDatabase.instance.reference().child("donor");
This is UI area
enter code here
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(1500, 0, 5, 1),
title: Text('Donor Registration'),
),
body: Padding(
padding: const EdgeInsets.all(10),
child: ListView(
children: <Widget>[
Container(
height: 100,
width: 100,
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: 65.0,
child: Image.asset('lib/assets/logo.png'))),
FormBuilder(
// context,
key: _fbKey,
// autovalidate: true,
readOnly: false,
child: Column(
children: <Widget>[
Text('Personal Information'),
SizedBox(height: 15),
FormBuilderTextField(
attribute: 'Name',
controller: _nameController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
icon: Icon(
Icons.account_circle,
color: Color.fromRGBO(255, 0, 0, 1),
),
labelText: 'Full Name',
hintText: 'Enter Your Full name',
),
validators: [
FormBuilderValidators.required(
errorText: 'This field required')
],
keyboardType: TextInputType.name,
//controller: _nameController,
),
SizedBox(height: 25),
FormBuilderRadioGroup(
attribute: 'radio_group',
decoration: const InputDecoration(
//value: gender,
border: OutlineInputBorder(),
icon: Icon(
Icons.person_pin,
color: Color.fromRGBO(255, 0, 0, 1),
),
labelText: 'Gender'),
onChanged: _onChanged,
options: [
FormBuilderFieldOption(value: 'M', child: Text('Male')),
FormBuilderFieldOption(value: 'F', child: Text('Female')),
FormBuilderFieldOption(value: 'O', child: Text('Other')),
]
.map((_gender) => FormBuilderFieldOption(
value: _gender,
child: Text('$_gender'),
))
.toList(growable: false),
validators: [
FormBuilderValidators.required(
errorText: 'This field required')
],
),
SizedBox(height: 15),
FormBuilderTextField(
attribute: 'age',
// autovalidate: true,
controller: _ageController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Age',
icon: Icon(
Icons.confirmation_number,
color: Color.fromRGBO(255, 0, 0, 1),
),
),
validators: [
FormBuilderValidators.required(
errorText: 'This field required')
],
keyboardType: TextInputType.number,
),
FormBuilderSwitch(
label: Text('I Accept the tems and conditions'),
attribute: 'accept_terms_switch',
initialValue: true,
onChanged: _onChanged,
),
SizedBox(height: 15),
],
),
),
Row(
children: <Widget>[
Expanded(
child: MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
'Submit',
style: TextStyle(color: Colors.white),
),
onPressed: () {
if (_fbKey.currentState.validate()) {
dbRef.push().set({
"name": _nameController.text,
"age": _ageController.text,
"gender": _gender,
"disease": _diseaseController.text,
"blood_group": _blood,
"body_part": _donate,
"Hospitals": _hospital,
}).then((_) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Successfully Added')));
_ageController.clear();
_nameController.clear();
}).catchError((onError) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(onError)));
});
} else {
print(_fbKey.currentState.value);
print('validation failed');
}
},
),
),
SizedBox(width: 20),
Expanded(
child: MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
'Reset',
style: TextStyle(color: Colors.white),
),
onPressed: () {
_fbKey.currentState.reset();
},
)),
],
),
],
),
),
);
}
#override
void dispose() {
super.dispose();
_ageController.dispose();
_nameController.dispose();
}
}
please tell me what could be errors.

Type int is not a subtype of type String

So, my app worked perfectly until I called an image using Image.asset(widget.product_detail_picture).
Here's the error:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
The following assertion was thrown building ProductDetails(dirty, state:
ProductDetailsState#db131):
type 'int' is not a subtype of type 'String'
Either the assertion indicates an error in the framework itself, or we should
provide substantially more information in this error message to help you
determine and fix the underlying cause.
Here's my product details page code:
import 'package:flutter/material.dart';
final product_detail_name;
final product_detail_picture;
final product_detail_old_price;
final product_detail_new_price;
ProductDetails({
this.product_detail_name,
this.product_detail_picture,
this.product_detail_old_price,
this.product_detail_new_price,
});
#override
_ProductDetailsState createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
backgroundColor: Colors.red,
title: Text('HunkyBees'),
actions: <Widget>[
new IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {}),
new IconButton(
icon: Icon(
Icons.shopping_cart,
color: Colors.white,
),
onPressed: () {})
],
),
body: new ListView(
children: <Widget>[
new Container(
height: 300.0,
child: GridTile(
child: Container(
color: Colors.white,
child: Image.asset(widget.product_detail_picture),
)),
),
],
),
);
}
}
Here's my product page where am calling the product image from
import '../pages/product_details.dart';
class Products extends StatefulWidget {
#override
_ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
var product_list = [
{
"name": "Men Real Dress",
"picture": "images/products/blazer1.jpeg",
"old_price": 120,
"price": 85,
},
{
"name": "Red Dress",
"picture": "images/products/dress1.jpeg",
"old_price": 190,
"price": 80,
},
{
"name": "Women Dress",
"picture": "images/products/dress2.jpeg",
"old_price": 100,
"price": 59,
},
{
"name": "Women Hills",
"picture": "images/products/hills1.jpeg",
"old_price": 140,
"price": 90,
},
];
#override
Widget build(BuildContext context) {
return GridView.builder(
itemCount: product_list.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return Single_prod(
prod_name: product_list[index]['name'],
prod_picture: product_list[index]['picture'],
prod_old_price: product_list[index]['old_price'],
prod_price: product_list[index]['price'],
);
});
}
}
class Single_prod extends StatelessWidget {
final prod_name;
final prod_picture;
final prod_old_price;
final prod_price;
Single_prod(
{this.prod_name,
this.prod_picture,
this.prod_old_price,
this.prod_price});
#override
Widget build(BuildContext context) {
return Card(
child: Hero(
tag: prod_name,
child: Material(
child: InkWell(
onTap: () => Navigator.of(context).push(
new MaterialPageRoute(
//Passing Product Details Inside Navigation Co
builder: (context) => new ProductDetails(
product_detail_name: prod_name,
product_detail_picture: prod_old_price,
product_detail_new_price: prod_price,
product_detail_old_price: prod_old_price,
),
),
),
child: GridTile(
footer: Container(
color: Colors.white70,
child: ListTile(
leading: Text(
prod_name,
style: TextStyle(fontWeight: FontWeight.bold),
),
title: Text(
"\$$prod_price",
style: TextStyle(
color: Colors.red, fontWeight: FontWeight.w800),
),
subtitle: Text(
"\$$prod_old_price",
style: TextStyle(
color: Colors.black54,
fontWeight: FontWeight.w800,
decoration: TextDecoration.lineThrough),
),
),
),
child: Image.asset(
prod_picture,
fit: BoxFit.cover,
)),
),
),
),
);
}
}
It worked fine without adding:
child: Image.asset(widget.product_detail_picture), to the product_details page
It working fine without me calling the image.
In your Single_prod class, your argument to product_detail_picture is int or double by guessing your parsing arg varaible name(prod_old_price):
ProductDetails(
product_detail_name: prod_name,
product_detail_picture: prod_old_price, // this prod_old_price is not String
Its a good idea to take use of static type, instead of using dynamic type. One great benefit of the language you are missing and you are facing this issue, and that issue is you are not getting compile time error when you passing an int to String variable.
try to give a type like final String product_detail_picture, and make sure that product_detail_picture is a String not int.
final String product_detail_picture;
Image.asset must have String parameter like,
Image.asset('assets/images/cake.jpg'),

A RenderFlex overflowed by 40 pixels on the bottom problem

Another exception was thrown: A RenderFlex overflowed by 40 pixels on the bottom.
I am getting this error. Please someone help me. I am new in flutter.
I did change lots of things on the code but still couldn't change the result.
import 'package:flutter/material.dart';
import 'package:estilo/pages/cart.dart';
class Cart_products extends StatefulWidget {
#override
_Cart_productsState createState() => _Cart_productsState();
}
class _Cart_productsState extends State<Cart_products> {
var Products_on_the_cart = [
{
"name": "Blazer (Man)",
"picture": "images/products/blazer1.jpeg",
"price": 85,
"size": "M",
"color": "Black",
"quantity": 1
},
{
"name": "Hill 1",
"picture": "images/products/hills1.jpeg",
"price": 50,
"size": "38",
"color": "Red",
"quantity": 1
},
{
"name": "Hill 1",
"picture": "images/products/hills1.jpeg",
"price": 50,
"size": "38",
"color": "Red",
"quantity": 1
},
];
#override
Widget build(BuildContext context) {
return new ListView.builder(
itemCount: Products_on_the_cart.length,
itemBuilder: (context, index) {
return new Single_cart_product(
cart_prod_name: Products_on_the_cart[index]["name"],
cart_prod_color: Products_on_the_cart[index]["color"],
cart_prod_quantity: Products_on_the_cart[index]["quantity"],
cart_prod_size: Products_on_the_cart[index]["size"],
cart_prod_price: Products_on_the_cart[index]["price"],
cart_prod_picture: Products_on_the_cart[index]["picture"],
);
});
}
}
class Single_cart_product extends StatelessWidget {
final cart_prod_name;
final cart_prod_picture;
final cart_prod_price;
final cart_prod_size;
final cart_prod_color;
final cart_prod_quantity;
Single_cart_product(
{this.cart_prod_name,
this.cart_prod_picture,
this.cart_prod_price,
this.cart_prod_color,
this.cart_prod_quantity,
this.cart_prod_size});
#override
Widget build(BuildContext context) {
return Card(
child: ListTile(
//Leading Section
leading: new Image.asset(
cart_prod_picture,
width: 80.0,
height: 80.0,
),
//Title Section
title: new Text(cart_prod_name),
//Subtitle Section
subtitle: new Column(
children: <Widget>[
new Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0.0),
child: new Text("Size:")),
Padding(
padding: const EdgeInsets.all(4.0),
child: new Text(
cart_prod_size,
style: TextStyle(color: Colors.red),
)),
//For Product Color
new Padding(
padding: const EdgeInsets.fromLTRB(20.0, 8.0, 8.0, 8.0),
child: new Text("Color:"),
),
Padding(
padding: const EdgeInsets.all(4.0),
child: new Text(cart_prod_color,
style: TextStyle(color: Colors.red)),
)
],
),
// This is for product price
new Container(
alignment: Alignment.topLeft,
child: new Text(
"$cart_prod_price\₺",
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.red),
),
)
],
),
trailing: new Column(
verticalDirection: VerticalDirection.down,
children: <Widget>[
new IconButton(icon: Icon(Icons.arrow_drop_up), onPressed: (){}),
new IconButton(icon: Icon(Icons.arrow_drop_down), onPressed: (){})
],
),
),
);
}
}
this is my dart class
The screenshot is here
Try this, it will look like this:
#override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
return Card(
child: Row(
children: <Widget>[
new SizedBox(
width: (screenSize.width / 5) * 4.3,
child: ListTile(
//Leading Section
leading: new Image.asset(
cart_prod_picture,
width: 80.0,
height: 80.0,
),
//Title Section
title: new Text(cart_prod_name),
//Subtitle Section
subtitle: new Column(
children: <Widget>[
new Row(
children: <Widget>[
new Padding(
padding: const EdgeInsets.all(0.0),
child: new Text("Size:")),
new Padding(
padding: const EdgeInsets.all(4.0),
child: new Text(
cart_prod_size,
style: TextStyle(color: Colors.red),
)),
//For Product Color
new Padding(
padding: const EdgeInsets.fromLTRB(20.0, 8.0, 8.0, 8.0),
child: new Text("Color:"),
),
new Padding(
padding: const EdgeInsets.all(4.0),
child: new Text(cart_prod_color,
style: TextStyle(color: Colors.red)),
)
],
),
// This is for product price
new Container(
alignment: Alignment.topLeft,
child: new Text(
"$cart_prod_price\₺",
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.red),
),
)
],
),
),
),
new SizedBox(
width: 49.0,
child: new Column(
children: <Widget>[
new IconButton(icon: Icon(Icons.arrow_drop_up), onPressed: () {}),
new Text("$cart_prod_quantity"),
new IconButton(icon: Icon(Icons.arrow_drop_down), onPressed: () {})
],
)
)
],
),
);
}

Categories

Resources