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);
}
Related
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 "));
I have 2 things I want to compare and return a list of Strings for each of the matching Ids with the corresponding names. Example: I have a list of "genre_ids": [16, 878, 28] from a movie, and from another API I get a list of objects with id and name of the genres, { "id": 878, "name": "Science Fiction" }. Now I want to compare the list of genre_ids with the list of objects with ids and names and return a List of names with all the matching Ids. How do I do that? I tried using the .where() option but failed miserably.
JSON from genre list:
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 10749,
"name": "Romance"
},
{
"id": 878,
"name": "Science Fiction"
},
]
}
JSON from movie list:
"results": [
{
"adult": false,
"genre_ids": [
16,
878,
28
],
"id": 610150,
"release_date": "2022-06-11",
"title": "Dragon Ball Super: Super Hero",
"vote_average": 7.5,
"vote_count": 126
},
]
Both models from the APIs:
class Movies {
int? id;
String? title;
String? overview;
List<dynamic>? genreIds;
dynamic voteAverage;
String? posterPath;
Movies({
this.id,
this.title,
this.overview,
this.genreIds,
this.voteAverage,
this.posterPath,
});
Movies.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
overview = json['overview'];
genreIds = json['genre_ids'].toList();
voteAverage = json['vote_average'];
posterPath = json['poster_path'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = id;
data['title'] = title;
data['overview'] = overview;
data['vote_average'] = voteAverage;
data['genre_ids'] = genreIds;
data['poster_path'] = posterPath;
return data;
}
}
class Genres {
int? id;
String? name;
Genres({
this.id,
this.name,
});
Genres.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'] as String;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = id;
data['name'] = name;
return data;
}
}
API calls:
Future<List<Movies?>> getAllMovies() async {
Response response = await Dio().get(Contants().moviesUrl);
return (response.data['results'] as List).map((movies) {
return Movies.fromJson(genres);
}).toList();
}
Future<List<Genres?>> getAllGenres() async {
Response response = await Dio().get(Contants().genresUrl);
return (response.data['genres'] as List).map((genres) {
return Genres.fromJson(genres);
}).toList();
}
Future builder:
FutureBuilder(
future: Future.wait([
RepositoryFromAPItoDB().gettAllMovies(),
RepositoryFromAPItoDB().getAllGenres()
]),
builder:
(BuildContext context, AsyncSnapshot<List<dynamic>?> snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data?[0].length,
itemBuilder: (BuildContext context, int index) {
return MoviesListTile(
title: snapshot.data?[0][index].title,
voteAverage: snapshot.data?[0][index].voteAverage,
description: snapshot.data?[0][index].overview,
posterPath: snapshot.data?[0][index].posterPath,
genreIds: snapshot.data?[0][index].genreIds,
genres: ['drama', 'somehting'],
);
},
);
}
},
),
Requested output of names from the list:
Widget getTextWidgets(List<String?> strings) {
return Row(
children: strings
.map((item) => Container(
child: Text(
item!,
),
),
),
)
.toList());
}
Any form of help is appreciated.
Is this what you wanted?
void main() {
Map<String, dynamic> genres = {
"genres": [
{"id": 28, "name": "Action"},
{"id": 12, "name": "Adventure"},
{"id": 16, "name": "Animation"},
{"id": 35, "name": "Comedy"},
{"id": 10749, "name": "Romance"},
{"id": 878, "name": "Science Fiction"},
]
};
Map<String, dynamic> movie = {
"adult": false,
"genre_ids": [16, 878, 28],
"id": 610150,
"release_date": "2022-06-11",
"title": "Dragon Ball Super: Super Hero",
"vote_average": 7.5,
"vote_count": 126
};
print(getGenres(movie, genres["genres"]));
}
List getGenres(Map movie, List genres) {
final Set movieGenreIds = Set.from(movie["genre_ids"]);
return genres
.where((g) => movieGenreIds.contains(g["id"]))
.map((g) => g["name"])
.toList();
}
The output:
[Action, Animation, Science Fiction]
Edit, using the models you provided.
List getGenres(Movie movie, List<Genre> genres) {
final Set movieGenreIds = Set.from(movie.genreIds);
return genres
.where((g) => movieGenreIds.contains(g.id))
.map((g) => g.name)
.toList();
}
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 have an app in flutter want to add list of data to sqlite database at initializing the database ,I have problem with the type of model.
I have this model for data :
import 'dart:convert';
List<Clubs> clubsFromMap(String str) =>
List<Clubs>.from(json.decode(str).map((x) => Clubs.fromMap(x)));
String clubsToMap(List<Clubs> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toMap())));
class Clubs {
Clubs({
this.id,
this.club,
this.leagueId,
this.price,
this.surname,
this.leagueName,
this.counter,
this.selected,
});
int id;
String club;
int leagueId;
String price;
String surname;
String leagueName;
int counter;
String selected;
factory Clubs.fromMap(Map<String, dynamic> json) => Clubs(
id: json["id"],
club: json["club"],
leagueId: json["league_id"],
price: json["price"],
surname: json["surname"],
leagueName: json["league_name"],
counter: json["counter"],
selected: json["selected"],
);
Map<String, dynamic> toMap() => {
"id": id,
"club": club,
"league_id": leagueId,
"price": price,
"surname": surname,
"league_name": leagueName,
"counter": counter,
"selected": selected,
};
}
and I have this list of data for that model :
var clubs = [
{
"id": 1,
"club": "Manchester City",
"league_id": 1,
"price": "10.00",
"surname": "MCY",
"league_name": "Premier League",
"counter": 1,
"selected": "No"
},
..................etc
]
no I want tho add this initial data to sqflite database ,I created thsi :
import 'package:sqflite/sqflite.dart';
class DataBaseService {
static final DataBaseService _instance = DataBaseService.internal();
factory DataBaseService() => _instance;
DataBaseService.internal();
Database _database;
Future<Database> get database async {
if (_database == null) {
_database = await intializeDataBase();
return _database;
}
}
Future<Database> intializeDataBase() async {
var dir = await getDatabasesPath();
var path = dir + "clubs.db";
var database =
await openDatabase(path, version: 1, onCreate: (db, version) {
db.execute('''
create table $clubsTableName(
columnId integer primary key,
$columnClub text not null,
$columnLeaueId integer,
$columnPrice double,
$columnSurname text not null,
$columnLeagueName text,
$columnCounter integer.
$columnSelected text,
)
''');
db.insert(clubsTableName,clubs.toMap());
it say that toMap() isn't defined ,if I changed it to clubsFromMap(clubs) instead of clubs.toMap() it says : The argument type 'List<Clubs>' can't be assigned to the parameter type 'Map<String, Object>'.dart(argument_type_not_assignable)
How can I solve this?
I solved it after change the list format like this:
var clubs = {"data":{
{
"id": 1,
"club": "Manchester City",
"league_id": 1,
"price": "10.00",
"surname": "MCY",
"league_name": "Premier League",
"counter": 1,
"selected": "No"
},
..................etc}
}
I am getting a response as key as numeric. How to map data for the following response
{
"1": [
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
],
"2": [
{
"id": 9,
"name": "ttt1"
},
{
"id": 5,
"name": "ttt3"
}
],
"3": [
{
"id": 4,
"name": "ttg",
"status_id": 1
}
]
}
Here is my model
import 'dart:convert';
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
String homeBannerModelToJson(Map<String, List<HomeBannerModel>> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x.toJson())))));
class HomeBannerModel {
int id;
String name;
HomeBannerModel({this.id, this.name});
HomeBannerModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
name= json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
I need to take the value in UI as
var data1 = data['1'];
var data2= data['2'];
var data3= data['3'];
but I am getting errors. help how to get the data of each key in each of the variable
but while mapping I am getting errors I have added part of my code in UI
_message:"type 'Map<String, dynamic>' is not a subtype of type 'List'"
The following method will convert your json string to a valid map object so that you can get your data the way you wanted.
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
to access data
final data = homeBannerModelFromJson(your_json_string);
print(data['1'][0].name); // test 1
You current json structure is Map<String, List<Map<String, dynamic>>>
You can try something like
var json = {...};
json.forEach((key, list) {
list.forEach((homeBannerModelMap) {
HomeBannerModel hBM = HomeBannerModel.fromJson(homeBannerModelMap);
});
});
You getting the error because your data is the type of Map, not the List.
So you can do something like this:
// [data] is result banners
List data = [];
// [result] is your object variable {"1": [{"id": 1, "name": "Welcome!"}]} etc
// So .forEach method is used for iterating through your json object
result.forEach((k, v){
// in which iteration I will map every instance to List of [HomeBannerModel]
var value = v.map((banner) => HomeBannerModel.fromJson(banner)).toList();
//in result I will add the result to our [banners] List
data.add(value);
});
But in this case, you should do:
data1 = data[1] // use int as the key, result will be List of BannerModels [Instance of 'HomeBannerModel', Instance of 'HomeBannerModel']
instead of:
var data1 = data['1']; //use string as the key
Please try the following code with just one model 'HomeBannerModel'.
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final Map datas = {};
json.forEach((key, value) {
datas.addAll(
{"$key": value.map((ele) => HomeBannerModel.fromMap(ele)).toList()});
});
print(datas["1"]);
print(datas["2"]);
print(datas["3"]);
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
You may also try with two models (1) Data and (2) HomeBannerModel. Please see the following code :
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final List<Data> data = [];
json.forEach((key, value) {
data.add(Data.fromMap({"id": key, "details": value}));
});
print(data.firstWhere((e) => e.dataID == '1').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '2').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '3').homeBannerModel);
}
class Data {
final String dataID;
final List<HomeBannerModel> homeBannerModel;
Data({
this.dataID,
this.homeBannerModel,
});
factory Data.fromMap(Map<String, dynamic> map) {
if (map == null) return null;
return Data(
dataID: map["id"],
homeBannerModel: (map["details"]
.map<HomeBannerModel>((ele) => HomeBannerModel.fromMap(ele))
.toList() as List<HomeBannerModel>));
}
#override
String toString() => 'Data(id: $dataID, details: $homeBannerModel)';
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
From what I’m seeing in the sample response you shared , the kets are all string as should be... "1" is also String FYI.
Coming to the error you're getting its because you are probably using the var data1,data2,data3 as a map which it isn't.
var data1 = data['1'];
if you print this var you will get :
[
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
]
If you want to access the submap with id of 6 and name Test 1 do the following:
print(data1[0]);
to display name:
print(data1[0]["name"]);