Show all data from json list - android

I have this json -
[
{
"id": 1046474266,
"serviceTag": "5N4H3Z2",
"orderBuid": 1212,
"shipDate": "2019-11-29T06:00:00Z",
"productCode": ">/030",
"localChannel": "ENTP",
"productId": "latitude-14-5400-laptop",
"productLineDescription": "LATITUDE 5400",
"productFamily": "Unknown",
"systemDescription": "Latitude 5400",
"productLobDescription": "Latitude",
"countryCode": "SE",
"duplicated": false,
"invalid": false,
"entitlements": [
{
"itemNumber": "439-18919",
"startDate": "2019-11-30T00:00:00.22Z",
"endDate": "2025-02-26T23:59:59.224Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "PJ",
"serviceLevelDescription": "P, ProDeploy Basic Client",
"serviceLevelGroup": 8
},
{
"itemNumber": "709-16269",
"startDate": "2019-11-29T00:00:00.405Z",
"endDate": "2021-02-28T23:59:59.408Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "CB",
"serviceLevelDescription": "Collect and Return Initial with Dates",
"serviceLevelGroup": 5
},
{
"itemNumber": "723-42456",
"startDate": "2021-03-01T00:00:00.398Z",
"endDate": "2024-03-01T23:59:59.402Z",
"entitlementType": "EXTENDED",
"serviceLevelCode": "ND",
"serviceLevelDescription": "C, NBD ONSITE",
"serviceLevelGroup": 5
},
{
"itemNumber": "723-42453",
"startDate": "2019-11-29T00:00:00.987Z",
"endDate": "2021-02-28T23:59:59.991Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "ND",
"serviceLevelDescription": "C, NBD ONSITE",
"serviceLevelGroup": 5
}
]
},
{
"id": 1039573973,
"serviceTag": "3Z2N9Y2",
"orderBuid": 1212,
"shipDate": "2019-11-01T05:00:00Z",
"productCode": ">/030",
"localChannel": "ENTP",
"productId": "latitude-14-5400-laptop",
"productLineDescription": "LATITUDE 5400",
"productFamily": "Unknown",
"systemDescription": "Latitude 5400",
"productLobDescription": "Latitude",
"countryCode": "SE",
"duplicated": false,
"invalid": false,
"entitlements": [
{
"itemNumber": "709-16269",
"startDate": "2019-11-01T00:00:00.723Z",
"endDate": "2021-02-01T23:59:59.727Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "CB",
"serviceLevelDescription": "Collect and Return Initial with Dates",
"serviceLevelGroup": 5
},
{
"itemNumber": "723-42453",
"startDate": "2019-11-01T00:00:00.077Z",
"endDate": "2021-02-01T23:59:59.08Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "ND",
"serviceLevelDescription": "C, NBD ONSITE",
"serviceLevelGroup": 5
},
{
"itemNumber": "439-18919",
"startDate": "2019-11-02T00:00:00.733Z",
"endDate": "2025-01-29T23:59:59.737Z",
"entitlementType": "INITIAL",
"serviceLevelCode": "PJ",
"serviceLevelDescription": "P, ProDeploy Basic Client",
"serviceLevelGroup": 8
},
{
"itemNumber": "723-42456",
"startDate": "2021-02-02T00:00:00.053Z",
"endDate": "2024-02-02T23:59:59.056Z",
"entitlementType": "EXTENDED",
"serviceLevelCode": "ND",
"serviceLevelDescription": "C, NBD ONSITE",
"serviceLevelGroup": 5
}
]
}
]
And i want to show all 'serviceLevelDescription' for the same 'serviceTag'
this what i have done:
]1
so u can see that i got all i need but u can see that i got just the last value from 'serviceLevelDescription' not all 'serviceLevelDescription'
so how i can do it som i show all 'serviceLevelDescription'??
my code!!
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:dell_warranty/dellTok.dart';
import 'package:dell_warranty/model_json.dart';
import 'package:http/http.dart';
void main() => runApp(new MaterialApp(
home: new DellW(),
));
class DellW extends StatefulWidget {
#override
DellWState createState() => new DellWState();
}
class DellWState extends State<DellW> {
TextEditingController serviceTagg = TextEditingController();
List<ModelJson> _taggs;
StreamController _streamController;
Stream _stream;
static const String getToken =
"https://apigtwb2c.us.dell.com/auth/oauth/v2/token";
static const String apiUrl =
"https://apigtwb2c.us.dell.com/PROD/sbil/eapi/v5/asset-entitlements";
static DellTok dellTok;
static ModelJson modelJson;
search() async {
if (serviceTagg.text == null || serviceTagg.text.length == 0) {
_streamController.add(null);
return;
}
var queryParameters = {
'access_token': dellTok.accessToken.toString(),
'servicetags': serviceTagg.text.trim().toString()
};
var uri = Uri.https('apigtwb2c.us.dell.com',
'/PROD/sbil/eapi/v5/asset-entitlements', queryParameters);
var responseDell = await http.get(uri, headers: {});
print(responseDell.body);
_streamController.add(json.decode(responseDell.body));
}
#override
void initState() {
super.initState();
_streamController = StreamController();
_stream = _streamController.stream;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("LOAD"),
bottom: PreferredSize(
preferredSize: Size.fromHeight(48.0),
child: Row(
children: <Widget>[
Expanded(
child: Container(
margin: const EdgeInsets.only(left: 12.0, bottom: 8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24.0),
),
child: TextFormField(
controller: serviceTagg,
decoration: InputDecoration(
hintText: "Search for a word",
contentPadding: const EdgeInsets.only(left: 24.0),
border: InputBorder.none,
),
),
),
),
IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {
search();
},
)
],
),
),
),
body: Container(
margin: const EdgeInsets.all(8.0),
child: StreamBuilder(
stream: _stream,
builder: (BuildContext ctx, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: Text("Enter a search word"),
);
}
if (snapshot.data == "waiting") {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListBody(
children: <Widget>[
Container(
color: Colors.grey[300],
child: ListTile(
leading: snapshot.data[index]["serviceTag"] == null
? null
: Text(
snapshot.data[index]["serviceTag"],
),
title: Text(snapshot.data[index]
["productLineDescription"] ==
null
? null
: snapshot.data[index]["productLineDescription"] +
")"),
),
),
Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot.data[index]
["productLobDescription"] ==
null
? null
: snapshot.data[index]
["productLobDescription"]),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new Text(snapshot.data[index]["entitlements"]
[index]["startDate"] ==
null
? null
: snapshot.data[index]["entitlements"][index]
["startDate"]),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot.data[index]["entitlements"]
[index]["endDate"] ==
null
? null
: snapshot.data[index]["entitlements"][index]
["endDate"]),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot.data[index]["entitlements"]
[index]["entitlementType"] ==
null
? null
: snapshot.data[index]["entitlements"][index]
["entitlementType"]),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot.data[index]["entitlements"]
[index]["serviceLevelDescription"] ==
null
? null
: snapshot.data[index]["entitlements"][index]
["serviceLevelDescription"]),
),
],
),
)
],
);
},
);
},
),
),
);
}
}

I can see that you have an array that you want to show, with your current code you're accessing just one index ([index]["serviceLevelDescription"]) that's why you're getting just one result shown.
You can create a new function responsible for populating the array. then pass the entitlements array property onto that function - like so - [index]["entitlements"]
renderServiceLevelDescription(entitlementsArray) {
return Row(children: entitlementsArray.map((entitlement) =>
Flexible(
child: Text(entitlement["serviceLevelDescription"]), //You can edit this / style as you like
)
).toList());
}
You then update your card code to invoke this!
Hope this helps :)

Related

Flutter List UI

I am correctly building an application with flutter and while searching for some ideas i came across this list and I wanted to ask how I can get these results?
https://dribbble.com/shots/15932824--Transactions-Overview-Detailview
The last image where it says 30 June 2021, under that the list is like connected is there a way to achieve this? Thanks in advance I hope I was clear.
class MyHomePage extends StatelessWidget {
final List<Map<String, dynamic>> dispalyList = [
{
"date": "30 june 2021",
"amount": "10000",
"items": [
{
"product": "Fintroy",
"amount": "100",
"product_desc": "Purchase on site",
},
{
"product": "Consta coffee",
"amount": "5",
"product_desc": "Purchase on store",
},
]
},
{
"date": "24 june 2021",
"amount": "5000",
"items": [
{
"product": "ATM Withdrow",
"amount": "100",
"product_desc": "Sale earnings",
},
{
"product": "Consta coffee",
"amount": "4",
"product_desc": "Purchase on shop",
},
]
}
];
MyHomePage({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: ListView.builder(
itemCount: dispalyList.length,
itemBuilder: (context, index) {
final List<Map<String, dynamic>> productList =
dispalyList[index]["items"];
return Column(
children: [
Row(
children: [
Text(dispalyList[index]["date"] ?? ""),
const Spacer(),
Text(dispalyList[index]["amount"] ?? ""),
],
),
const SizedBox(height: 12),
Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
borderRadius:
const BorderRadius.all(Radius.circular(12))),
child: ListView.separated(
physics:
const NeverScrollableScrollPhysics(), // AVOID CHILD LISTVIEW SCROLL
separatorBuilder: (context, index) => const Divider(),
shrinkWrap: true,
itemCount: productList.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
const CircleAvatar(
backgroundColor: Colors.amber,
),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(productList[index]["product"]),
Text(productList[index]["product_desc"])
],
),
const Spacer(),
Text(productList[index]["amount"])
],
),
);
},
),
),
const SizedBox(height: 12),
],
);
},
),
),
);
}
}

Json is not responding

i am trying to initialize json data in my widget but for some reason, it is not responding. i am pretty new to dealing with json called locally and this is one of them. i have already done all the necessary things like creating the file to put the data and passing it through the pubspec. still it is not responding. here is the json data
[
{
"_id":"636e0ce55270d648e9a5248a",
"index":0,
"guid":"58e73438-27fa-48bf-8127-ff4e42beaac5",
"isActive":true,
"price":"$252.77",
"name":"James Lewis Blue Ledis",
"type":"dress",
"image":"https://images.unsplash.com/photo-1539008835657-9e8e9680c956?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80"
},
{
"_id":"636e0ce573d4e1ce44e5a5a9",
"index":1,
"guid":"e1d93cfe-b15a-4969-97e0-3b6b9ae967d0",
"isActive":false,
"price":"$289.88",
"name":"Blue FLower Shoe",
"type":"apparel",
"image":"https://images.unsplash.com/photo-1543163521-1bf539c55dd2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80"
},
{
"_id":"636e0ce522bd392da7b43d2e",
"index":2,
"guid":"0ee56032-db50-44c3-9234-5e213b8fde22",
"isActive":false,
"price":"$452.81",
"name":"Yellow Blight Bag",
"type":"bag",
"image":"https://images.pexels.com/photos/934673/pexels-photo-934673.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"recommended":true
},
{
"_id":"636e0ce5fdf98a105a5c14cb",
"index":3,
"guid":"fee6217c-ee7f-4e3e-91cc-24dfd91d6cfc",
"isActive":true,
"price":"$244.91",
"name":"Black meter dress",
"type":"dress",
"image":"https://images.unsplash.com/photo-1550639525-c97d455acf70?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=726&q=80"
},
{
"_id":"636e0ce5036de010a96ab185",
"index":4,
"guid":"2d9e8b22-90c1-4979-b904-2cc164626e10",
"isActive":false,
"price":"$335.17",
"name":"Dynamic Pink Lobre",
"type":"bag",
"image":"https://images.unsplash.com/photo-1566150905458-1bf1fc113f0d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1171&q=80"
},
{
"_id":"636e0ce52e2a60eed71c79b6",
"index":5,
"guid":"32db02a5-a12d-4f3e-a601-787211734ab1",
"isActive":false,
"price":"$414.69",
"name":"Gucci Flems Onyx",
"type":"bag",
"image":"https://images.unsplash.com/photo-1548036328-c9fa89d128fa?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1169&q=80"
},
{
"_id":"636e0ce52f14c39bb8366650",
"index":6,
"recommended":true,
"guid":"1a0c388c-2ac7-4a49-85ba-50b12bc08f28",
"isActive":true,
"price":"$293.63",
"name":"705 California",
"type":"apparel",
"image":"https://images.unsplash.com/photo-1618354691229-88d47f285158?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=715&q=80"
},
{
"_id":"636e0ce56b57e56f54676302",
"index":7,
"guid":"956527b1-c9d8-4c18-a6ef-e4b1dcd76640",
"isActive":false,
"price":"$293.57",
"name":"Mid-week flavors",
"type":"apparel",
"image":"https://images.unsplash.com/photo-1560769629-975ec94e6a86?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80"
},
{
"_id":"636e0ce56c0ed15b28297895",
"index":8,
"guid":"119db62a-eaba-493f-b73a-5dcba04b69c1",
"isActive":false,
"price":"$348.63",
"name":"Hermes Coysx",
"type":"bag",
"image":"https://images.unsplash.com/photo-1594223274512-ad4803739b7c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=757&q=80"
},
{
"_id":"636e0ce58d2cbb1e636f1829",
"index":9,
"guid":"40011d30-d06d-4a72-b119-0826dc79c138",
"isActive":true,
"price":"$337.91",
"name":"Kirsten Gilliam",
"type":"dress",
"image":"https://images.unsplash.com/photo-1543163521-1bf539c55dd2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80"
},
{
"_id":"636e0ce5713679af9a884699",
"index":10,
"guid":"f5dbfba4-fbe2-475b-98fc-36ff42daad91",
"isActive":false,
"price":"$436.62",
"recommended":true,
"name":"Outcast white",
"type":"t-shirt",
"image":"https://images.unsplash.com/photo-1527719327859-c6ce80353573?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80"
},
{
"_id":"636e0ce5578fa1d92624204f",
"index":11,
"guid":"805df707-3833-4e5f-9e09-0c59053750cb",
"isActive":false,
"price":"$493.15",
"name":"Peace Skull",
"type":"t-shirt",
"image":"https://images.unsplash.com/photo-1503341504253-dff4815485f1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80"
},
{
"_id":"636e0ce5bd29b6bd570aef00",
"index":12,
"guid":"32e75d5c-ea59-4c23-8d85-29dd37040a7d",
"isActive":false,
"price":"$350.71",
"name":"Louis Vuiton Brown bag",
"type":"bag",
"image":"https://images.pexels.com/photos/3661622/pexels-photo-3661622.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
},
{
"_id":"636e0ce505794be5900eb9ad",
"index":13,
"guid":"44aa2a9a-e1c9-4004-b681-ce246e5a8ee4",
"isActive":true,
"price":"$271.21",
"name":"Impulso Supreme",
"type":"t-shirt",
"recommended":true,
"image":"https://images.unsplash.com/photo-1627933540891-1fb6a397c89b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80"
}
]
and this is where it is being called
class ExploreCollections extends StatefulWidget {
const ExploreCollections({Key? key}) : super(key: key);
#override
State<ExploreCollections> createState() => _ExploreCollectionsState();
}
class _ExploreCollectionsState extends State<ExploreCollections> {
final List _items = [];
Future<void> readJson() async{
final String response = await rootBundle.loadString('assets/model/clothes.json');
final data = await json.decode(response);
}
#override
void initState() {
_items.shuffle();
super.initState();
}
int _activeIndex = 0;
final List<Widget> _images = [
Stack(
children: [
Image.asset('assets/images/image 10.png'),
Padding(
padding: const EdgeInsets.only(left: 55.0, top: 230),
child: Text(
'Luxury \n Fashion \n &Accessories'.toUpperCase(),
style: TextStyle(
fontFamily: 'Bodoni',
fontSize: 40,
fontWeight: FontWeight.w500,
color: Colors.grey.shade700
),
),
),
Padding(
padding: const EdgeInsets.only(top: 400.0),
child: Center(
child:SvgPicture.asset('assets/iconImages/Button.svg'),
),
),
],
),
Stack(
children: [
Image.asset('assets/images/leeloo.jpeg'),
],
),
Stack(
children: [
Image.asset('assets/images/ayaka.jpeg'),
],
),
];
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 5,
child: Column(
children: [
Stack(
children: [
CarouselSlider.builder(
options: CarouselOptions(
viewportFraction: 1,
aspectRatio: 1.8,
height: MediaQuery.of(context).size.height*0.8,
autoPlay: false,
initialPage: 0,
enableInfiniteScroll: false,
enlargeCenterPage: true,
onPageChanged: (index, reason){
setState(() {
_activeIndex = index;
});
}
),
itemCount: _images.length,
itemBuilder: (BuildContext context, int index, int realIndex) {
return GestureDetector(
onTap: (){
Navigator.of(context).pushNamedAndRemoveUntil(BlackScreen.routeName, (route) => false);
},
child: _images[index]);
},
),
Padding(
padding: const EdgeInsets.only(top: 565.0),
child: Center(
child: buildIndicator(),
),
),
],
),
SvgPicture.asset('assets/images/Title.svg'),
const SizedBox(
height: 10,),
TabBar(
indicator: CircleTabIndicator(color: Colors.redAccent, radius: 3),
tabs: [
Tab(child: Text('All',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Apparel',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Dress',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Tshirt',style: TextStyle(color: Colors.grey.shade600),),),
Tab(child: Text('Bag',style: TextStyle(color: Colors.grey.shade600),),),
]
),
Container(
height: 60,
child: TabBarView(
children: [
All(items: _items),
Center(child: Text('Apparel'),),
Center(child: Text('Dress'),),
Center(child: Text('Tshirt'),),
Center(child: Text('Bag'),),
]
),
)
],
),
);
}
i finally passed it to the 'All class'
class All extends StatelessWidget {
final List items;
const All({Key? key, required this.items}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index){
return Text(items[index]['name']);
});
}
}
As a first step you should change the type of your _list variable to Map<String,dynamic>
And change readJson method return type
Future<Map<String,dynamic>> readJson() async{
final String response = await rootBundle.loadString('assets/model/clothes.json');
return await json.decode(response);
}
And call readJson in initState like so
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
readJson().then((value) =>_items = value);
});
super.initState();
}
This should do the trick

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.

Why my value is not updating in GetX Flutter

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.

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(),
);
}
}

Categories

Resources