How to create a class of List of arrays and fetch data in flutter - arraylist

I'm trying to build a class provider as a list of arrays in order to fetch the data from API, but I'm unable to find a sufficient way thats working in order to fetch the data. I keep getting constant errors. And I cant figure out how to make a list of the Arrays with the class values.
Here is how the code in the API looks(will change the real values just to show an example):
{
"listProduct": [
{
"id": 127,
"title": "String",
"Date": "2019-10-31T10:03:35",
"Price": 25.0,
"category": "Jeep",
"brand": "مرسيدس",
"brandModel": "M300",
"kilometer": 300.0,
"modelYear": "2010",
"fuelType": "بنزين",
"gearType": "اوتوماتك",
"image": {
"path": "Upload/UploadCarMain/UploadCarMain-200-200/car.jpeg",
"name": "car.jpeg"
},
],
}
Here is my class provider data which are supposed to be in an array (this has all the values that will be put into the "listProduct"):
class AddCar {
int id;
String name;
String city;
String country;
String currencyT;
double price;
String date;
String sponsNum;
String category;
String company;
String model;
String year;
String engine;
double distanceCovered;
String transmission;
String oilT;
String outColor;
String inColor;
String description;
File image;
PlaceLocation location;
bool isFavorite;
AddCar({
this.id,
this.name,
this.city,
this.country,
this.currencyT,
this.price,
this.date,
this.sponsNum,
this.category,
this.company,
this.model,
this.year,
this.engine,
this.distanceCovered,
this.transmission,
this.oilT,
this.outColor,
this.inColor,
this.description,
this.image,
this.location,
this.isFavorite = false,
});
}
Here is my fetch code (these are the values i need to fetch for my current code displayed):
Future<void> fetchAndSetCars() async {
const url =
'My link';
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
List<AddCar> loadedCars = [];
extractedData.forEach((carId, carData) {
loadedCars.add(AddCar(
id: int.parse(carId),
name: carData['Title'],
currencyT: carData['gearType'],
price: carData['Price'],
date: carData['Date'],
model: carData['brandModel'],
year: carData['modelYear'],
distanceCovered: carData['kilometer'],
transmission: carData['gearType'],
oilT: carData['fuelType'],
image: File(carData['image']),
));
});
_cars = loadedCars;
print(json.decode(response.body));
notifyListeners();
}
here is where I display my fetch code:
class CarArea extends StatefulWidget {
#override
_CarAreaState createState() => _CarAreaState();
}
class _CarAreaState extends State<CarArea> {
var _isInit = true;
#override
void didChangeDependencies() {
if (_isInit) {
Provider.of<Cars>(context).fetchAndSetCars();
}
_isInit = false;
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
final carsData = Provider.of<Cars>(context);
final car = carsData.cars;
return car.isEmpty
? Padding(
padding: EdgeInsets.all(15.0),
child: Center(
child: Text(
'no cars available',
style: TextStyle(
fontFamily: ArabicFonts.Tajawal,
fontWeight: FontWeight.bold,
package: 'google_fonts_arabic',
),
)))
: car.length < 2
? ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: car.length = 1,
shrinkWrap: true,
itemBuilder: (ctx, i) => CarItem(
car[i].id,
car[i].image,
car[i].name,
car[i].model,
car[i].currencyT,
car[i].price,
car[i].distanceCovered,
car[i].transmission,
car[i].oilT,
car[i].year,
car[i].date,
),
)
: ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: car.length = 2,
shrinkWrap: true,
itemBuilder: (ctx, i) => CarItem(
car[i].id,
car[i].image,
car[i].name,
car[i].model,
car[i].currencyT,
car[i].price,
car[i].distanceCovered,
car[i].transmission,
car[i].oilT,
car[i].year,
car[i].date,
),
);
}
}
And my CarItem where the code is displayed to the UI:
class CarItem extends StatelessWidget {
final int id;
final File image;
final String name;
final String model;
final String currencyT;
final double price;
final double distanceCovered;
final String transmission;
final String oilT;
final String year;
final String date;
CarItem(
this.id,
this.image,
this.name,
this.model,
this.currencyT,
this.price,
this.distanceCovered,
this.transmission,
this.oilT,
this.year,
this.date,
);
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).primaryColor, width: 2.0),
),
),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromARGB(255, 245, 245, 245),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(17.0, 4.0, 17.0, 4.0),
child: Row(
textDirection: TextDirection.rtl,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: Row(
textDirection: TextDirection.rtl,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(5.0, 0, 0, 0),
child: Icon(
MyFlutterApp.cars,
),
),
Text(
AppLocalizations.of(context).itemListCar,
),
],
),
),
Container(
child: Row(
children: <Widget>[
Text(
date.toString(),
),
Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 5.0, 0),
child: Icon(
MyFlutterApp.history,
),
),
],
),
),
],
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 0.35,
height: MediaQuery.of(context).size.width * 0.35,
child: GestureDetector(
child: image == null
? Container(
decoration: BoxDecoration(
color: Colors.grey[200],
),
padding: EdgeInsets.all(6),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'No Images provided',
textAlign: TextAlign.center,
),
],
),
)
: Image.file(
image,
fit: BoxFit.fill,
),
onTap: () {
Navigator.of(context).pushNamed(
MyCarDetails.routeName,
arguments: id,
);
},
),
),
Container(
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.all(0),
padding: const EdgeInsets.fromLTRB(22.0, 5.0, 22.0, 0),
child: Column(
children: <Widget>[
Container(
width: double.infinity,
padding: EdgeInsets.only(
bottom: 5.8,
top: 0,
),
child: Text(
name,
)),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Text(
model,
),
),
Text(
currencyT + price.toStringAsFixed(1),
),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Tab(
icon: Icon(
MyFlutterApp.km,
),
child: Text(
distanceCovered.toStringAsFixed(0) + ' KM',
),
),
Tab(
icon: Icon(
MyFlutterApp.motion_vector,
),
child: Text(
transmission,
),
),
Tab(
icon: Icon(
MyFlutterApp.fuel_type,
),
child: Text(
oilT,
),
),
Tab(
icon: Icon(
MyFlutterApp.general_model,
),
child: Text(
year,
),
),
],
),
),
],
),
),
],
),
],
),
);
}
}
here is the error i get in my stacktrace:
E/flutter (29729): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)
E/flutter (29729): listProduct
E/flutter (29729): ^
E/flutter (29729):
E/flutter (29729): #0 int._throwFormatException (dart:core-patch/integers_patch.dart:131:5)
E/flutter (29729): #1 int._parseRadix (dart:core-patch/integers_patch.dart:142:16)
E/flutter (29729): #2 int._parse (dart:core-patch/integers_patch.dart:100:12)
E/flutter (29729): #3 int.parse (dart:core-patch/integers_patch.dart:63:12)
E/flutter (29729): #4 Cars.fetchAndSetCars.<anonymous closure>
package:flutter_app/providers/car_provider.dart:107
E/flutter (29729): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (29729): #6 Cars.fetchAndSetCars
package:flutter_app/providers/car_provider.dart:105
E/flutter (29729): <asynchronous suspension>
E/flutter (29729): #7 _CarAreaState.didChangeDependencies
E/flutter (29729): #8 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4086
E/flutter (29729): #9 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3919
E/flutter (29729): #10 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #11 Element.updateChild
package:flutter/…/widgets/framework.dart:2904
E/flutter (29729): #12 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3961
E/flutter (29729): #13 Element.rebuild
package:flutter/…/widgets/framework.dart:3738
E/flutter (29729): #14 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:3924
E/flutter (29729): #15 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3919
E/flutter (29729): #16 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #17 Element.updateChild
E/flutter (29729): #18 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3961
E/flutter (29729): #19 Element.rebuild
package:flutter/…/widgets/framework.dart:3738
E/flutter (29729): #20 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:3924
E/flutter (29729): #21 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4088
E/flutter (29729): #22 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3919
E/flutter (29729): #23 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #24 MultiChildRenderObjectElement.mount
package:flutter/…/widgets/framework.dart:5233
E/flutter (29729): #25 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #26 Element.updateChild
package:flutter/…/widgets/framework.dart:2904
E/flutter (29729): #27 SingleChildRenderObjectElement.mount
E/flutter (29729): #28 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #29 Element.updateChild
package:flutter/…/widgets/framework.dart:2904
E/flutter (29729): #30 SingleChildRenderObjectElement.mount
package:flutter/…/widgets/framework.dart:5127
E/flutter (29729): #31 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #32 Element.updateChild
package:flutter/…/widgets/framework.dart:2904
E/flutter (29729): #33 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3961
E/flutter (29729): #34 Element.rebuild
package:flutter/…/widgets/framework.dart:3738
E/flutter (29729): #35 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:3924
E/flutter (29729): #36 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3919
E/flutter (29729): #37 Element.inflateWidget
E/flutter (29729): #38 Element.updateChild
package:flutter/…/widgets/framework.dart:2904
E/flutter (29729): #39 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3961
E/flutter (29729): #40 Element.rebuild
package:flutter/…/widgets/framework.dart:3738
E/flutter (29729): #41 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:3924
E/flutter (29729): #42 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3919
E/flutter (29729): #43 ParentDataElement.mount
package:flutter/…/widgets/framework.dart:4314
E/flutter (29729): #44 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3101
E/flutter (29729): #45 Element.updateChild
package:flutter/…/widgets/framework.dart:2904
E/flutter (29729): #46 Componen
print gave me this:
{listProduct: [{id: 127, Title: car -en, Date: 2019-10-31T10:03:35, Price: 25.0, category: car child 2, categoryId: 8, status: 1, brandId: 1, brand: mercedes, brandModelId: 6, brandModel: M300, kilometer: 300.0, modelYearId: 2, modelYear: 2010, fuelType: benz, carFeatureFuelId: 3, gearType: automatic, carFeatureGearId: 2, image: {path: Upload/UploadCarMain/UploadCarMain-200-200/carCar127.jpeg, name: carCar127.jpeg}, vendorId: 2}, {id: 44, Title: null, Date: 2019-10-26T09:16:23.0265211, Price: 3454.0, category: car child 1, categoryId: 7, status: 1, brandId: 2, brand: BM, brandModelId: 7, brandModel: BM X5, kilometer: 345.0, modelYearId: 2, modelYear: 2010, fuelType: dezil, carFeatureFuelId: 4, gearType: normal, carFeatureGearId: 1, image: {path: Upload/UploadCarMain/UploadCarMain-200-200/1Car44.jpg, name: 1Car44.jpg}, vendorId: 1}, {id: 43, Title: null, Date: 2019-10-25T09:40:46.4631028, Price: 25.0, category: car child 1, categoryId: 7, status: 1, brandId: 1, brand: mercedes, brandModelId: 6,
after printing loadedCars:
[{id: 127, Title: car -en, Date: 2019-10-31T10:03:35, Price: 25.0, category: car child 2, categoryId: 8, status: 1, brandId: 1, brand: mercedes, brandModelId: 6, brandModel: M300, kilometer: 300.0, modelYearId: 2, modelYear: 2010, fuelType: benz, carFeatureFuelId: 3, gearType: automatic, carFeatureGearId: 2, image: {path: Upload/UploadCarMain/UploadCarMain-200-200/carCar127.jpeg, name: carCar127.jpeg}, vendorId: 2}, {id: 44, Title: null, Date: 2019-10-26T09:16:23.0265211, Price: 3454.0, category: car child 1, categoryId: 7, status: 1, brandId: 2, brand: BM, brandModelId: 7, brandModel: BM X5, kilometer: 345.0, modelYearId: 2, modelYear: 2010, fuelType: dezil, carFeatureFuelId: 4, gearType: normal, carFeatureGearId: 1, image: {path: Upload/UploadCarMain/UploadCarMain-200-200/1Car44.jpg, name: 1Car44.jpg}, vendorId: 1}, {id: 43, Title: null, Date: 2019-10-25T09:40:46.4631028, Price: 25.0, category: car child 1, categoryId: 7, status: 1, brandId: 1, brand: mercedes, brandModelId: 6, brandModel

First of all you have to access the listProduct by this.
final response = await http.get(url);
final extractedData = json.decode(response.body);
List loadedCars = extractedData['listProduct'];
for(var i in loadedCars) {
_cars.add(AddCar(
id: i["id"],
name: i['Title'],
currencyT: i['gearType'],
price: i['Price'],
date: i['Date'],
model: i['brandModel'],
year: i['modelYear'],
distanceCovered: i['kilometer'],
transmission: i['gearType'],
oilT: i['fuelType'],
image: File(i['image']),
));
}
This way you will create a data arraylist and in view you have to access the
that arraylist _cars.
Hope it will help you.

Related

Flutter Error Valid value range is empty: 0

This error keeps coming up after my CircularProgressIndicator() is finished running for some time. I have no idea, why is this error coming and how can i fix it. I read the answers for the similar question asked before and tried them, but nothing changed. I am not sure that is this caused by my ListView.builder() or something else.
Here's the code -
main.dart -
import 'package:flutter/material.dart';
import 'package:soccer_app/api_manager.dart';
import 'package:soccer_app/pagerbody.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SoccerApp(),
);
}
}
class SoccerApp extends StatefulWidget {
#override
_SoccerAppState createState() => _SoccerAppState();
}
class _SoccerAppState extends State<SoccerApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFFAFAFA),
appBar: AppBar(
backgroundColor: Color(0xFFFAFAFA),
elevation: 0.5,
title: Text('SoccerBoard', style: TextStyle(color: Colors.black),),
centerTitle: true,
),
body: FutureBuilder(
future: SoccerApi().getAllMatches(),
builder: (context, snapshot) {
if(snapshot.hasData) {
return PageBody(snapshot.data);
}
else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
Pagebody.dart -
import 'package:flutter/material.dart';
import 'package:soccer_app/goal_stat.dart';
import 'package:soccer_app/matchtile.dart';
import 'package:soccer_app/soccermodel.dart';
import 'package:soccer_app/teamstats.dart';
Widget PageBody(List<SoccerMatch> allmatches){
return Column(
children: [
Expanded(
flex: 2,
child: Container(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 18.0, vertical: 24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
teamStat("Local Team", allmatches[0].home.logoUrl, allmatches[0].home.name),
goalStat(allmatches[0].fixture.status.elapsedTime, allmatches[0].goal.home, allmatches[0].goal.away),
teamStat("Visitor Team", allmatches[0].away.logoUrl, allmatches[0].away.name),
],
),
),
),
),
Expanded(
flex: 5,
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xff4373d9),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40.0),
topRight: Radius.circular(40.0),
),
),
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"MATCHES",
style: TextStyle(
color: Colors.white,
fontSize: 24.0,
),
),
Expanded(
child: ListView.builder(
itemCount: allmatches.length,
itemBuilder: (context, index){
return MatchTile(allmatches[index]);
},
),
),
],
),
),
),
),
],
);
}
And this is the error -
The following RangeError was thrown building FutureBuilder<List<SoccerMatch>>(dirty, state: _FutureBuilderState<List<SoccerMatch>>#2a0fc):
RangeError (index): Invalid value: Valid value range is empty: 0
The relevant error-causing widget was:
FutureBuilder<List<SoccerMatch>> file:///C:/Users/Hp/AndroidStudioProjects/soccer_app/lib/main.dart:36:13
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:177:60)
#1 PageBody (package:soccer_app/pagerbody.dart:19:50)
#2 _SoccerAppState.build.<anonymous closure> (package:soccer_app/main.dart:40:20)
#3 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:751:55)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (10805): Api service: {get: fixtures, parameters: [], errors: {required: At least one parameter is required.}, results: 0, paging: {current: 1, total: 1}, response: []}
the list coming from your API is empty thus
List<SoccerMatch> allmatches is empty
and you are trying to call allmatches[0] (trying to access the first element of an empty list) so here is your error

Remove bottom line on DateTimePicker

HelloEverybody,
I hope that you are doing well.
I am trying to remove bottom line on datetimepicker in Flutter but I do not find the solution. Some help would be greatly appreciated.
Many thanks.
Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(2.0, 2.0, 15.0, 1.0),
child: DateTimePicker(
decoration: InputDecoration(
border: InputBorder.none,
),
type: DateTimePickerType.dateTimeSeparate,
dateMask: 'd MMM yyyy',
controller: _controlerTaskDueDate,
//initialValue: DateTime.now().toString(),
firstDate: DateTime(2020),
lastDate: DateTime(2200),
icon: Padding(
padding: const EdgeInsets.fromLTRB(5.0, 4.0, 0.0, 1.0),
child: Icon(Icons.event),
),
dateLabelText: 'Due Date',
timeLabelText: "Due Time",
//use24HourFormat: false,
selectableDayPredicate: (date2) {
if (date2.weekday == 6 || date2.weekday == 7) {
return true;
}
return true;
},
onChanged: (valDueDate) => setState(() => _valueTaskDueDateChanged = valDueDate),
validator: (valDueDate) {
setState(() => _valueTaskDueDateToValidate = valDueDate);
return null;
},
onSaved: (valDueDate) => setState(() => _valueTaskDueDateSaved = valDueDate),
),
),
),
Within your DateTimePicker() widget, add this decoration:
decoration: InputDecoration(
border: InputBorder.none,
),
UPDATE:
Since my previous answer was overriding the DateTimePicker decorations, I found this to work:
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: //your card widget,
),

Cant get data's length in itemCount

I want to get my API data's length to use in Listview.builder widget. I want to get my data from API which is 'mahalle'. And this data is a list of data. I want to get this data's length to build a list. But I got an error like this:
#4 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4546
...
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Class 'Future<dynamic>' has no instance getter 'length'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: length
The relevant error-causing widget was
MahalleList
And the reference of the error is :
#action
Future<void> fetcMahalle() async {
// var data =
// await httpClient.getData(globals.SELECT_URL).then((mahalle) => mahalle);
networkService.getMahalle();
}
And I'm getting my data with :
Future getMahalle() async {
BaseOptions options = new BaseOptions(
baseUrl: globals.PROD_URL,
connectTimeout: 5000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);
dio.options.headers["Authorization"] = "Bearer ${globals.USER_TOKEN}";
try {
var response =
await dio.get(globals.SELECT_URL); //'api/hizlirapor/selects'
List<MahalleModel> mahalleList = response.data['mahalle']
.map<MahalleModel>((mahalle) => MahalleModel.fromJson(mahalle))
.toList();
return mahalleList;
} on DioError catch (e) {
debugPrint("ERRORR!!!!!!!!!!!!! ${e.error.toString()}");
return null;
}
}
And finally here's the widget I'm trying to use my list data's length :
Container _buildBody(
BuildContext context, ObservableFuture<List<MahalleModel>> future) {
return Container(
color: backgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
_buildSearchBar(context),
RefreshIndicator(
onRefresh: mahalleStore.fetcMahalle,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: mahalleList.length,
itemBuilder: (context, index) {
final mahalle = mahalleList[index];
return Container(
height: 100,
child: Card(
color: Colors.white,
margin: EdgeInsets.all(15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
color: mainColor,
width: 3,
height: 50,
),
SizedBox(
width: 15,
),
Icon(
AppIcon.mahalle_raporu,
color: mainColor,
),
SizedBox(
width: 15,
),
Text(
mahalle.mahalleAdi,
style: textStyle,
),
],
),
),
);
}),
),
],
),
);
}
Thanks for your all help !
FutureBuilder(
future:mahalleStore.fetchMahalle,
builder: (context, snapshot){
//whatever returns from this function, will be avaliable inside snapshot paremeter.
final mahalleList= snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
{
return Center(child: CircularProgressIndicator(),);
}
case ConnectionState.done:
if (snapshot.hasData) {
// do what you want here
}
return Text("Error occured");
default:
//
}});
I deleted previous comment , check this one.
You should use FutureBuilder because getMahalle returns a Future.

Flutter input decoration suffixIcon not appearing but always showing cross symbol

I have the following example codes. I have now managed to put the prefixicon and it works fine. I want to move the same icon the suffix meaning on the right hand side but it just does not work but the X symbol it what appears.
Here is a screen shot.
I have added the following lines suffixIcon: IconButton( but it seems not be appearing but the one on the left hand side which is the prefix appears perfectly fine. I cant get the one on the right hand side. What is blocking it from appearing?
Below is my codes.
class MyHomePageState extends State<MyHomePage> {
// Show some different formats.
final formats = {
//InputType.both: DateFormat("EEEE, MMMM d, yyyy 'at' h:mma"),
//InputType.date: DateFormat('dd/MM/yyyy'),
//InputType.time: DateFormat("HH:mm"),
InputType.date: DateFormat("d MMMM yyyy"),
};
//InputType.date: DateFormat('yyyy-MM-dd'),
// Changeable in demo
InputType inputType = InputType.date;
bool editable = true;
DateTime date;
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(appName)),
body: Padding(
padding: EdgeInsets.all(16.0),
child: ListView(
children: <Widget>[
Form(
//key: _myKey,
child: Column(
children : [
new Container(
width: 200.0,
child:new DateTimePickerFormField(
dateOnly: true,
format: formats[inputType],
editable: false,
validator: (val) {
if (val != null) {
return null;
} else {
return 'Date Field is Empty';
}
},
/*decoration: InputDecoration(
border: InputBorder.none,
labelText: 'From',contentPadding: const EdgeInsets.symmetric(horizontal: 20.0)),*/
decoration: InputDecoration(
hintText: 'To',
border: InputBorder.none,
filled: false,
prefixIcon: Icon(
Icons.arrow_drop_down,
color: Colors.blue,
size: 28.0,
),
suffixIcon: IconButton(
icon: Icon(Icons.arrow_drop_down,size: 28),
onPressed: () {
debugPrint('222');
})),
initialValue: DateTime.now().subtract(new Duration(days: 7)), //Add this in your Code.
),
)
]
),
),
RaisedButton(
onPressed: () {
/*if (_myKey.currentState.validate()) {
_myKey.currentState.save();
} else {
}*/ print("check;");
if(emailController.text.isEmpty){
print("TEST;");
//valid = false;
//emailError = "Email can't be blank!";
//openAlertBox();
Toast.show("Empty Date From", context, backgroundColor: Colors.red );
}
else{
print("not empty;");
final f = new DateFormat('yyyy-MM-dd');
final original = new DateFormat('d MMMM yyyy');
print("Format datre is"+emailController.text);
print("Formate date :"+original.parse(emailController.text).toString());
}
},
child: Text('Submit'),
)
],
),
));
I re-created your case by singling out only the TextFormField code you provided and was able to see the dropdown arrow as suffixIcon.
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: MediaQuery
.of(context)
.size
.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children : [
new Container(
color: Colors.yellow,
width: 200.0,
child: TextFormField(
decoration: InputDecoration(
hintText: 'To',
border: InputBorder.none,
filled: false,
prefixIcon: Icon(
Icons.arrow_drop_down,
color: Colors.blue,
size: 28.0,
),
suffixIcon: IconButton(
icon: Icon(Icons.arrow_drop_down,size: 28),
onPressed: () {
debugPrint('222');
})),
),
)
]
)
),
)
);
}
}
I see that you used Padding as your body to return Scaffold. Try to replace it with Center or Container
You may have discovered the following but posting just in case...
The 'X' displayed is the reset icon for the date field ie. you use that to clear the field. You can turn it off with DateTimePickerFormField property 'resetIcon: null;' but then the only way to remove a date from the field is to ensure 'editable: true', which is the default but you have overridden it in your code.
Hope that helps.

App crashes without any logs when using some plugins to access device Contacts

I want to show contacts in my app for which I tried using contacts_service and contacts_plugin but my app crashes when I run it after installing the packages. I have just imported the file and written no code. I don't see any logs also.
Any other way of integrating contacts in my app would also be of great help!
You really need to learn and master the tools you need to use to develop Flutter applications.
And you really need to explain better your needs when you post a question on SO.
That said I've had a quick try on contacts_plugin and contact_service.
Do not use both, they are made for the same purpose. Choose one or the other.
It seems that contact_service is more stable: a weighted score of 92 over 82.
Android
Trying using contacts_plugin I guess you jad this error:
* What went wrong:
The Android Gradle plugin supports only Kotlin Gradle plugin version 1.2.51 and higher. Project 'contacts_plugin' is using version 1.2.30.
That because the contacts_plugin use kotlin version 1.2.30 and you have AS >= 3.2 like me.
ext.kotlin_version = '1.2.30'.
If you wanna give this a try you can clone the project and include the dependency this way:
contacts_plugin:
path: ../flutter-contacts-plugin/
and change in the plugin build.gradle this line:
ext.kotlin_version = '1.2.30'
with this
ext.kotlin_version = '1.2.51'
Even the iOS Project has problems if you use contact_plugins.
contact_serivce instead it works fine either on Android and on iOS.
Anyway always remember that on Android you need to add this permissions in you AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
and on iOS make sure to set NSContactsUsageDescription in the Info.plist file
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
And create a Flutter project with Swift support.
You can use the default example provided by the contact_service plugin to start learning:
import 'package:flutter/material.dart';
import 'package:contacts_service/contacts_service.dart';
void main() => runApp(ContactsExampleApp());
class ContactsExampleApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(routes: <String, WidgetBuilder>{
'/add': (BuildContext context) => AddContactPage()
}, home: ContactListPage());
}
}
class ContactListPage extends StatefulWidget {
#override
_ContactListPageState createState() => _ContactListPageState();
}
class _ContactListPageState extends State<ContactListPage> {
Iterable<Contact> _contacts;
#override
initState() {
super.initState();
refreshContacts();
}
refreshContacts() async {
var contacts = await ContactsService.getContacts();
setState(() {
_contacts = contacts;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Contacts Plugin Example')),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.of(context).pushNamed("/add").then((_) {
refreshContacts();
});
}),
body: SafeArea(
child: _contacts != null
? ListView.builder(
itemCount: _contacts?.length ?? 0,
itemBuilder: (BuildContext context, int index) {
Contact c = _contacts?.elementAt(index);
return ListTile(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) =>
ContactDetailsPage(c)));
},
leading: (c.avatar != null && c.avatar.length > 0)
? CircleAvatar(backgroundImage: MemoryImage(c.avatar))
: CircleAvatar(
child: Text(c.displayName.length > 1
? c.displayName?.substring(0, 2)
: "")),
title: Text(c.displayName ?? ""),
);
},
)
: Center(child: CircularProgressIndicator()),
),
);
}
}
class ContactDetailsPage extends StatelessWidget {
ContactDetailsPage(this._contact);
final Contact _contact;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar:
AppBar(title: Text(_contact.displayName ?? ""), actions: <Widget>[
FlatButton(
child: Icon(Icons.delete),
onPressed: () {
ContactsService.deleteContact(_contact);
})
]),
body: SafeArea(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Name"),
trailing: Text(_contact.givenName ?? "")),
ListTile(
title: Text("Middle name"),
trailing: Text(_contact.middleName ?? "")),
ListTile(
title: Text("Family name"),
trailing: Text(_contact.familyName ?? "")),
ListTile(
title: Text("Prefix"), trailing: Text(_contact.prefix ?? "")),
ListTile(
title: Text("Suffix"), trailing: Text(_contact.suffix ?? "")),
ListTile(
title: Text("Company"),
trailing: Text(_contact.company ?? "")),
ListTile(
title: Text("Job"), trailing: Text(_contact.jobTitle ?? "")),
AddressesTile(_contact.postalAddresses),
ItemsTile("Phones", _contact.phones),
ItemsTile("Emails", _contact.emails)
],
),
));
}
}
class AddressesTile extends StatelessWidget {
AddressesTile(this._addresses);
final Iterable<PostalAddress> _addresses;
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ListTile(title: Text("Addresses")),
Column(
children: _addresses
.map((a) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
children: <Widget>[
ListTile(
title: Text("Street"),
trailing: Text(a.street)),
ListTile(
title: Text("Postcode"),
trailing: Text(a.postcode)),
ListTile(
title: Text("City"), trailing: Text(a.city)),
ListTile(
title: Text("Region"),
trailing: Text(a.region)),
ListTile(
title: Text("Country"),
trailing: Text(a.country)),
],
),
))
.toList())
]);
}
}
class ItemsTile extends StatelessWidget {
ItemsTile(this._title, this._items);
final Iterable<Item> _items;
final String _title;
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ListTile(title: Text(_title)),
Column(
children: _items
.map((i) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: ListTile(
title: Text(i.label ?? ""),
trailing: Text(i.value ?? ""))))
.toList())
]);
}
}
class AddContactPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => _AddContactPageState();
}
class _AddContactPageState extends State<AddContactPage> {
Contact contact = Contact();
PostalAddress address = PostalAddress(label: "Home");
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Add a contact"),
actions: <Widget>[
FlatButton(
onPressed: () {
_formKey.currentState.save();
contact.postalAddresses = [address];
ContactsService.addContact(contact);
Navigator.of(context).pop();
},
child: Icon(Icons.save, color: Colors.white))
],
),
body: Container(
padding: EdgeInsets.all(12.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
TextFormField(
decoration: const InputDecoration(labelText: 'First name'),
onSaved: (v) => contact.givenName = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Middle name'),
onSaved: (v) => contact.middleName = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Last name'),
onSaved: (v) => contact.familyName = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Prefix'),
onSaved: (v) => contact.prefix = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Suffix'),
onSaved: (v) => contact.suffix = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Phone'),
onSaved: (v) =>
contact.phones = [Item(label: "mobile", value: v)],
keyboardType: TextInputType.phone),
TextFormField(
decoration: const InputDecoration(labelText: 'E-mail'),
onSaved: (v) =>
contact.emails = [Item(label: "work", value: v)],
keyboardType: TextInputType.emailAddress),
TextFormField(
decoration: const InputDecoration(labelText: 'Company'),
onSaved: (v) => contact.company = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Job'),
onSaved: (v) => contact.jobTitle = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Street'),
onSaved: (v) => address.street = v),
TextFormField(
decoration: const InputDecoration(labelText: 'City'),
onSaved: (v) => address.city = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Region'),
onSaved: (v) => address.region = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Postal code'),
onSaved: (v) => address.postcode = v),
TextFormField(
decoration: const InputDecoration(labelText: 'Country'),
onSaved: (v) => address.country = v),
],
)),
),
);
}
}