Related
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
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.
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.
I am trying to make a flutter web form using stepper and i am doing the experiment for small size screen. I have done the vertical scroll using the physics: ClampingScrollPhysics() method. However, I am unable to make horizontal scroll inside the stepper step. I want to make the radio button horizontally scroll able so that the error message will hide and i the text goes out of the screen, the user can scroll to that part. I already used SingleChildCcrollView(crollDirection: Axis.horizontal) but it didn't work. The image is
The code for the flutter program is as below: -
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Stepper Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Stepper Tutorial'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentStep = 0;
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController addressController = TextEditingController();
List<String> demoList = [];
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
),
Expanded(
child: SingleChildScrollView(
// scrollDirection: Axis.horizontal,
child: Stepper(
physics: ClampingScrollPhysics(),
steps: _mySteps(),
currentStep: this._currentStep,
onStepTapped: (step) {
setState(
() {
this._currentStep = step;
},
);
},
onStepContinue: () {
setState(
() {
if (this._currentStep < this._mySteps().length - 1) {
this._currentStep = this._currentStep + 1;
}
},
);
},
onStepCancel: () {
setState(
() {
if (this._currentStep > 0) {
this._currentStep = this._currentStep - 1;
} else {
this._currentStep = 0;
}
},
);
},
),
),
),
demoList.isEmpty
? Text("")
: Column(
children: demoList.map((e) {
return Text(e);
}).toList(),
),
ElevatedButton(
onPressed: () {
demoList = [];
viewList();
},
child: Text("Click to see List"),
),
],
),
);
}
viewList() {
if (nameController.text.isEmpty ||
emailController.text.isEmpty ||
addressController.text.isEmpty) {
setState(
() {
if (nameController.text.isEmpty) {
demoList.add("Name field is empty");
} else if (emailController.text.isEmpty) {
demoList.add("Email field is Empty");
} else if (addressController.text.isEmpty) {
demoList.add("Address field is empty");
}
},
);
} else {
demoList.add(nameController.text);
demoList.add(emailController.text);
demoList.add(addressController.text);
setState(
() {
demoList = demoList;
},
);
}
}
List<Step> _mySteps() {
List<Step> _steps = [
Step(
title: Text('Name'),
content: TextField(
controller: nameController,
),
isActive: _currentStep >= 0,
),
Step(
title: Text('Email'),
content: TextField(
controller: emailController,
),
isActive: _currentStep >= 1,
),
Step(
title: Text('Address'),
content: TextField(
controller: addressController,
),
isActive: _currentStep >= 2,
),
Step(
title: Text('Number'),
content: Row(
children: <Widget>[
SingleChildScrollView(
physics: ClampingScrollPhysics(),
),
SafeArea(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Form(
child: Row(
children: <Widget>[
Radio(
value: "1",
),
Text("1"),
Radio(
value: "2",
),
Text("2"),
Radio(
value: "3",
),
Text("3"),
Radio(
value: "4",
),
Text("4"),
Radio(
value: "5",
),
Text("5"),
Radio(
value: "6",
),
Text("6"),
Radio(
value: "7",
),
Text("7"),
Radio(
value: "8",
),
Text("8"),
Radio(
value: "9",
),
Text("9"),
],
),
),
),
)
],
),
isActive: _currentStep >= 2,
),
];
return _steps;
}
}
You can just use a ListView and set the scrollDirection to horizontal. The Container is there because it needs something to give it a size.
Step(
title: Text('Number'),
content: Container(
height: 100,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Radio(
value: "1",
),
Center(child: Text("1")),
Radio(
value: "2",
),
Center(child: Text("1")),
Radio(
value: "3",
),
Center(child: Text("3")),
Radio(
value: "4",
),
Center(child: Text("4")),
Radio(
value: "5",
),
Center(child: Text("5")),
Radio(
value: "6",
),
Center(child: Text("6")),
Radio(
value: "7",
),
Center(child: Text("7")),
Radio(
value: "8",
),
Center(child: Text("8")),
Radio(
value: "9",
),
Center(child: Text("9")),
],
),
),
isActive: _currentStep >= 2,
),
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 :)