I have a following list and I want to add new items to that list when I click a button. How to achieve it?
List<dynamic> list = [
{
'id': 0,
'leading': 'Payment Application',
'trailing': 'System',
},
{
'id': 1,
'leading': 'Reference Number',
'trailing': 'SYM12113OI',
},
{
'id': 2,
'leading': 'Total',
'trailing': '\$15.00',
},
{
'id': 3,
'leading': 'Details',
'trailing': 'Civil Employment',
},
];
Try the following code:
TextButton(
child: Text("child"),
onPressed: () {
list.add(value);
}
),
1st create a Model for Your List Object :
Example:
// To parse this JSON data, do
//
// final listModel = listModelFromJson(jsonString);
import 'dart:convert';
List<ListModel> listModelFromJson(String str) => List<ListModel>.from(json.decode(str).map((x) => ListModel.fromJson(x)));
String listModelToJson(List<ListModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ListModel {
ListModel({
this.id,
this.leading,
this.trailing,
});
int id;
String leading;
String trailing;
factory ListModel.fromJson(Map<String, dynamic> json) => ListModel(
id: json["id"],
leading: json["leading"],
trailing: json["trailing"],
);
Map<String, dynamic> toJson() => {
"id": id,
"leading": leading,
"trailing": trailing,
};
}
Now You can define your List Like this:
List<ListModel> _list = [];
For Add Data In your List you can do :
_list.add(ListModel(id:1022,leading:"leading name",trailing:"training part "));
Related
I've come across a problem which I cannot figure out. I'm trying to display single event on my home screen which is next upcoming by date. That event comes from list of events in the api.
Currently I am using listview.builder to display those events however when I set item count to 1 I cannot get the next event by date to be displayed. I was trying to display all events in listview.builder and then filter but I couldn't get it to work.
I need to display events in that order but they need to be shown 1 by 1 based on todays time. So when current time is the same as the events time next event will be shown:
firstImage
And this is what I'm getting when the itemCount is 1. This is the last event from the list
which I tried to reverse but no success. secondImage
This is code for the ListView.builder
ListView.builder(
reverse: true,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
// itemCount: 1,
itemCount: 1,
itemBuilder: (context, index) {
var x = eventController.event.value!.data![index];
DateTime formattedStartDate = new DateFormat('yyyy-MM-dd hh:mm')
.parse(eventController
.event.value!.data![index].eventStartDate
.toString());
DateTime splitStartDate = new DateTime(
formattedStartDate.year,
formattedStartDate.month,
formattedStartDate.day,
formattedStartDate.hour,
formattedStartDate.minute);
DateTime today = DateTime.now();
bool isAfter = splitStartDate.isAfter(today);
return Column(
children: [
isAfter == true
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetails(
event: eventController
.event.value!.data![index])));
},
child: EventTileMain(
eventController.event.value!.data![index]))
: Container()
],
);
});
This is model calss of event:
// To parse this JSON data, do
//
// final event = eventFromJson(jsonString);
import 'dart:convert';
Event eventFromJson(String str) => Event.fromJson(json.decode(str));
String eventToJson(Event data) => json.encode(data.toJson());
class Event {
Event({
this.success,
this.data,
this.code,
this.count,
});
bool? success;
List<Datum>? data;
int? code;
int? count;
factory Event.fromJson(Map<String, dynamic> json) => Event(
success: json["success"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
code: json["code"],
count: json["count"],
);
Map<String, dynamic> toJson() => {
"success": success,
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
"code": code,
"count": count,
};
}
class Datum {
Datum({
this.id,
this.postTitle,
this.postContent,
this.postName,
this.postUrl,
this.organizer,
this.venue,
this.category,
this.speaker,
this.eventStartDate,
this.eventEndDate,
this.eventDate,
this.featuredImage,
});
String? id;
String? postTitle;
String? postContent;
String? postName;
String? postUrl;
List<Category>? organizer;
List<Category>? venue;
List<Category>? category;
dynamic speaker;
String? eventStartDate;
String? eventEndDate;
DateTime? eventDate;
String? featuredImage;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["ID"],
postTitle: json["post_title"],
postContent: json["post_content"],
postName: json["post_name"],
postUrl: json["post_url"],
organizer: List<Category>.from(json["organizer"].map((x) => Category.fromJson(x))),
venue: List<Category>.from(json["venue"].map((x) => Category.fromJson(x))),
category: List<Category>.from(json["category"].map((x) => Category.fromJson(x))),
speaker: json["speaker"],
eventStartDate: json["event_start_date"],
eventEndDate: json["event_end_date"],
eventDate: DateTime.parse(json["event_date"]),
featuredImage: json["featured_image"],
);
Map<String, dynamic> toJson() => {
"ID": id,
"post_title": postTitle,
"post_content": postContent,
"post_name": postName,
"post_url": postUrl,
"organizer": List<dynamic>.from(organizer!.map((x) => x.toJson())),
"venue": List<dynamic>.from(venue!.map((x) => x.toJson())),
"category": List<dynamic>.from(category!.map((x) => x.toJson())),
"speaker": speaker,
"event_start_date": eventStartDate,
"event_end_date": eventEndDate,
"event_date": eventDate!.toIso8601String(),
"featured_image": featuredImage,
};
}
class Category {
Category({
this.id,
this.name,
});
int? id;
Name? name;
factory Category.fromJson(Map<String, dynamic> json) => Category(
id: json["id"],
name: nameValues.map[json["name"]],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": nameValues.reverse![name],
};
}
enum Name { AUDITORIUM, SEMINAR, XPOSURE, XPOSURE_INTERNATIONAL_PHOTOGRAPHY_FESTIVAL, TOR_SEIDEL, XPOSURE_AUDITORIUM }
final nameValues = EnumValues({
"Auditorium": Name.AUDITORIUM,
"Seminar": Name.SEMINAR,
"Tor Seidel": Name.TOR_SEIDEL,
"Xposure": Name.XPOSURE,
"Xposure Auditorium": Name.XPOSURE_AUDITORIUM,
"Xposure International Photography Festival": Name.XPOSURE_INTERNATIONAL_PHOTOGRAPHY_FESTIVAL
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String>? reverseMap;
EnumValues(this.map);
Map<T, String>? get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
API call
class EventApi {
static var client = http.Client();
static Future<Event?> fetchEvents() async {
final response = await client.get(Uri.parse(
'https://xposure.ae/api/v1/events/'));
// 'https://xposure.ae/wp-json/wp/auditorium/v1/events'));
if (response.statusCode == 200) {
var jsonString = response.body;
return eventFromJson(jsonString);
} else {
return null;
}
}
}
If you need more information please let me know.
you can try this:
ListView.builder(
reverse: true,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
// itemCount: 1,
itemCount: 1,
itemBuilder: (context, index) {
var now = DateTime.now();
Datum? closestEvent;
eventController.event.value!.data!.forEach((element) {
var elementDate =
DateFormat('yyyy-MM-dd hh:mm').parse(element.eventStartDate);
if (closestEvent == null) {
if (elementDate.isAfter(now)) {
closestEvent = element;
}
} else {
var closestDate = DateFormat('yyyy-MM-dd hh:mm').parse(closestEvent!.eventStartDate);
if (elementDate.isAfter(now) && elementDate.isBefore(closestDate)) {
closestEvent = element;
}
}
});
return Column(
children: [
isAfter == true
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetails(
event: closestEvent)));
},
child: EventTileMain(
closestEvent))
: Container()
],
);
});
you can simply make a widget function and remove your listview, like this:
Widget buildEventWidget(BuildContext context){
var now = DateTime.now();
Datum? closestEvent;
eventController.event.value!.data!.forEach((element) {
var elementDate =
DateFormat('yyyy-MM-dd hh:mm').parse(element.eventStartDate);
if (closestEvent == null) {
if (elementDate.isAfter(now)) {
closestEvent = element;
}
} else {
var closestDate = DateFormat('yyyy-MM-dd hh:mm').parse(closestEvent!.eventStartDate);
if (elementDate.isAfter(now) && elementDate.isBefore(closestDate)) {
closestEvent = element;
}
}
});
return Column(
children: [
isAfter == true
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetails(
event: closestEvent)));
},
child: EventTileMain(
closestEvent))
: Container()
],
);
}
I'm trying to make a simple ListView with GetX but it gives me this error when starting the app "Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.", I'm new to flutter and dart, that's why I'm starting with the "easiest" and for work reasons they ask me to add GetX
Home
class HomePage extends GetView<HomeController> {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
// final homeController = Get.put(HomeController());
var title = "HomePage";
return Scaffold(
body: Obx(() {
HomeController controller = Get.find<HomeController>();
return controller.regionList.isEmpty
? const Center(
child: Text('No hay regiones'),
)
: ListView.builder(
itemCount: controller.regionList.length,
itemBuilder: (context, index) => ListTile(
title: Text(
controller.regionList[index].name,
)));
}),
);
}
}
Controller
class HomeController extends GetxController {
//late Regiones model;
var regionList = <Regiones>[].obs;
Future<List<Regiones>> getRegiones() async {
var response = await rootBundle.loadString('assets/response.json');
var results = (jsonDecode(response)['regions'] ?? []) as List;
return results.map((x) => Regiones.fromJson(x)).toList();
//return Regiones.fromJson(jsonDecode(response));
}
//Json['regions'] == null ? Null :
#override
Future<void> onInit() async {
// TODO: implement onInit
super.onInit();
regionList.assignAll(await getRegiones());
}
}
Json
{
"name": "Chile",
"regions": [
{
"name": "Arica y Parinacota",
"romanNumber": "XV",
"number": "15",
"abbreviation": "AP",
"communes": [
{ "name": "Arica", "identifier": "XV-1" },
{ "name": "Camarones", "identifier": "XV-2" },
{ "name": "General Lagos", "identifier": "XV-3" },
{ "name": "Putre", "identifier": "XV-4" }
]
},
{
...
Model
Regiones regionesFromJson(String str) => Regiones.fromJson(json.decode(str));
String regionesToJson(Regiones data) => json.encode(data.toJson());
class Regiones {
Regiones({
required this.name,
required this.regions,
});
String name;
List<Region> regions;
factory Regiones.fromJson(Map<String, dynamic> json) => Regiones(
name: json["name"],
regions:
List<Region>.from(json["regions"].map((x) => Region.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"regions": List<dynamic>.from(regions.map((x) => x.toJson())),
};
}
class Region {
Region({
required this.name,
required this.romanNumber,
required this.number,
required this.abbreviation,
required this.communes,
});
String? name;
String? romanNumber;
String? number;
String? abbreviation;
List<Commune> communes;
factory Region.fromJson(Map<String, dynamic> json) => Region(
name: json["name"],
romanNumber: json["romanNumber"],
number: json["number"],
abbreviation: json["abbreviation"],
communes: List<Commune>.from(
json["communes"].map((x) => Commune.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"romanNumber": romanNumber,
"number": number,
"abbreviation": abbreviation,
"communes": List<dynamic>.from(communes.map((x) => x.toJson())),
};
}
class Commune {
Commune({
required this.name,
required this.identifier,
});
String name;
String identifier;
factory Commune.fromJson(Map<String, dynamic> json) => Commune(
name: json["name"],
identifier: json["identifier"] ?? '',
);
Map<String, dynamic> toJson() => {
"name": name,
"identifier": identifier,
};
}
You call ['regions'] in two place:
1:
var results = (jsonDecode(response)['regions'] ?? []) as List;
2: inside Regiones.fromJson
so in your HomeController instead of this:
return results.map((x) => Regiones.fromJson(x)).toList();
try this:
return results.map((x) => Region.fromJson(x)).toList();
and then make your getRegiones return Future<List> like this:
Future<List<Regione>> getRegiones() async {
...
}
I have a JSON object here:
{
"data": [
{
"id": 1,
"countryName": "India"
},
{
"id": 2,
"countryName": "USA"
}
],
"exceptionInfo": null,
"message": null,
"messages": null,
"isSuccess": true
}
I want to fetch the name parameter under data to a DropDownMenuList. I have a data model here:
import 'dart:convert';
GetCountry getCountryFromJson(String str) => GetCountry.fromJson(json.decode(str));
String getCountryToJson(GetCountry data) => json.encode(data.toJson());
class GetCountry {
GetCountry({
this.data,
this.exceptionInfo,
this.message,
this.messages,
this.isSuccess,
});
List<CountryModal> data;
dynamic exceptionInfo;
dynamic message;
dynamic messages;
bool isSuccess;
factory GetCountry.fromJson(Map<String, dynamic> json) => GetCountry(
data: List<CountryModal>.from(json["data"].map((x) => CountryModal.fromJson(x))),
exceptionInfo: json["exceptionInfo"],
message: json["message"],
messages: json["messages"],
isSuccess: json["isSuccess"],
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"exceptionInfo": exceptionInfo,
"message": message,
"messages": messages,
"isSuccess": isSuccess,
};
}
class CountryModal {
CountryModal({
this.id,
this.countryName,
});
int id;
String countryName;
factory CountryModal.fromJson(Map<String, dynamic> json) => CountryModal(
id: json["id"],
countryName: json["countryName"],
);
Map<String, dynamic> toJson() => {
"id": id,
"countryName": countryName,
};
}
The function to fetch the data is below and is the indifferent file:
Future<GetCountry> Getcountry(String authToken) async{
try {
String uriParts = apiEndPoint.getUriParts('location/GetCountries');
var response = await http.get(
apiEndPoint.getHTTPUri(uriParts),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authToken
},
);
var responseJson = jsonDecode(response.body);
GetCountry country = GetCountry.fromJson(responseJson);
return country;
}
catch (err) {
debugPrint(err.toString());
throw err;
}
}
This method fetches the item successfully into a ListView.builder widget but I am a bit lost on how to fetch this to a List<DropdownMenuItem> items.
I have tried going through solutions but nothing seems to work for me.
please help.
EDIT:-
Below is the code for the dropdown list -:
List<CountryModal> _countrylist = [];
String mycountry;
DropdownButton(
items: _countrylist.map((item) {
return new DropdownMenuItem(
child: new Text(
item.countryName,
style: TextStyle(fontSize: 14.0),
),
value: item.id.toString(),
);
}).toList(),
hint: Text(
"Please select the country",
style: TextStyle(
color: Colors.black45,
),),
onChanged: (newVal) {
setState(() {
mycountry = newVal;
});
},
value: mycountry,
),
Error message below -:
Sample json format -:
{
"error": "0",
"message": "Succesfully fetched",
"status": true,
"data": [
{
"id": "5df0b94841f0331baf1357bb",
"stateName": "test group",
},
{
"id": "5df0df507091683d2f1ad0cf",
"stateName": "new group",
}
]
}
You will just pass a map.toList() to the items field.
DropdownButton(items: myGetCountry.map((CountryModal e) {
return DropdownMenuItem(child: SomeWidget(e))).toList();
})
I'm new to flutter and I'm practicing flutter and I want prepopulated database on button click I want to insert 10 data at once. The code is working but it is inserting in a repetition manner i.e. 1 will be inserted 2 or three times but I want to insert 10 rows of data in the database without repetition here is my Model:
import 'package:get/state_manager.dart';
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.tfModel,
});
List<TfModel> tfModel;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
tfModel: List<TfModel>.from(json["TfModel"].map((x) => TfModel.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"TfModel": List<dynamic>.from(tfModel.map((x) => x.toJson())),
};
}
class TfModel {
TfModel({
required this.id,
required this.content,
required this.moredesc,
});
int id;
String content;
String moredesc;
final isFavorite = false.obs;
factory TfModel.fromJson(Map<String, dynamic> json) => TfModel(
id: json["id"],
content: json["content"],
moredesc: json["moredesc"],
);
Map<String, dynamic> toJson() => {
"id": id,
"content": content,
"moredesc": moredesc,
};
}
database Helper for insetting Data to the database:
newClient(TfModel newClient) async {
final db = await database;
var raw = await db.rawInsert(
"INSERT Into QList (id,content,moredesc)"
" VALUES (?,?,?)",
[newClient.id, newClient.content, newClient.moredesc]);
return raw;
}
On my homepage, I have created model data and when the user clicks the start button data starts to be inserted into the database.
onPressed action on homepage.dart
onPressed: () async {
print(testClients.length);
for (int i = 0; i <= 9; i++) {
TfModel rnd = testClients[testClients.length-1];
try {
await DBProvider.instance.newClient(rnd);
}
on DatabaseException catch (e){
print("Database Exception");
print(e);
}
}
},
testClient array is below:
List<TfModel> testClients = [
TfModel(id: 1,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 2,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 3,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 4,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 5,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 6,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 7,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 8,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 9,
content: "Test",
moredesc: "Test Data"),
TfModel(id: 10,
content: "Test",
moredesc: "Test Data"),
];
Future<void> insertFeeds(List<s.Feeds> feeds) async {
final db = await banco;
var list = [];
feeds.forEach((element) => list.add(element.toMap()));
await db!.rawInsert(
'INSERT INTO feeds(editorial_id,feed_id,remessa,total_comments,total_reactions,user_reaction,texto,last_update) VALUES(?, ?, ?,?, ?, ?, ?, ?)',
list);
}
my json=
{
"result": {
"name": "json1",
"pages": [{
"zones": [{
"title": "title1"
},
{
"title": "title2"
}],
"id": 4
},
{
"zones": [{
"title": "title3"
},
{
"title": "title4"
}],
"id": 12
}],
"creatorUserName": "admin",
"id": 2
}
}
futurebuilder code
List post = snapshot.data["result"]["pages"];
return new Stack(
children: post.where((val) => val["id"] == 4).map((post) {
for (var item in post['zones']) {
print("title "+ item['title']);
Container(
child: Text(item["title"]),
); //Container
}
}).toList(),
); //Stack
Error code: Stack's children must not contain any null values, but a null value was found at index 0
enter image description here
help how can to build an algorithms
if get id = 4 zones -> Text(title1), Text(title2),
else id empty zones -> Text(title1), Text(title2), zones -> Text(title3), Text(title4),
Try
List post = snapshots.data["result"]["pages"];
First Make a model class for your JSON response using this amazing webpage, after that you can easily. call the needed data
import 'dart:convert';
YourModelClassName yourModelClassNameFromJson(String str) => YourModelClassName.fromJson(json.decode(str));
String yourModelClassNameToJson(YourModelClassName data) => json.encode(data.toJson());
class YourModelClassName {
Result result;
YourModelClassName({
this.result,
});
factory YourModelClassName.fromJson(Map<String, dynamic> json) => YourModelClassName(
result: Result.fromJson(json["result"]),
);
Map<String, dynamic> toJson() => {
"result": result.toJson(),
};
}
class Result {
String name;
List<Page> pages;
String creatorUserName;
int id;
Result({
this.name,
this.pages,
this.creatorUserName,
this.id,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
name: json["name"],
pages: List<Page>.from(json["pages"].map((x) => Page.fromJson(x))),
creatorUserName: json["creatorUserName"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"name": name,
"pages": List<dynamic>.from(pages.map((x) => x.toJson())),
"creatorUserName": creatorUserName,
"id": id,
};
}
class Page {
List<Zone> zones;
int id;
Page({
this.zones,
this.id,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
zones: List<Zone>.from(json["zones"].map((x) => Zone.fromJson(x))),
id: json["id"],
);
Map<String, dynamic> toJson() => {
"zones": List<dynamic>.from(zones.map((x) => x.toJson())),
"id": id,
};
}
class Zone {
String title;
Zone({
this.title,
});
factory Zone.fromJson(Map<String, dynamic> json) => Zone(
title: json["title"],
);
Map<String, dynamic> toJson() => {
"title": title,
};
}