i have an API that return data type of _HttpClientResponse cause i am using httpClient, i decode the result to string using the below
var reply = await memoryResponse.transform(utf8.decoder).join();
when i print the result
I/flutter (23708): String
I/flutter (23708): {"results":
[{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},
{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"}]}
then decode it with json.decod
var memJasonData = json.decode(reply);
when i print the runType
_InternalLinkedHashMap<String, dynamic>
{results:[{IPAddress": 192.1.1.1, Description: Windows 2016 Server},
{IPAddress: 192.1.1.1", Description : Windows 2016 Server },{ IPAddress :
192.1.1.1", Description : Windows 2016 Server }]}
i created a class to to be used here an i tried
List<Results> _getMemoryData1 = memJasonData.map((json) =>
Results.fromJson(json)).toList();
setState(() {
print(_getMemoryData1);
getMemoryData = _getMemoryData1;
print(getMemoryData);
also i tried to for lop after converting the map to list
var memToListData = memJasonData['results'] as List; '''
but nothing working with me
i appreciate your help
the function
''' var getMemoryData = const [];
Future _getMemoryData() async {
var url ='https://10.1.1.1/v3/Json/Query?query';
HttpClient client = new HttpClient();
client.addCredentials(Uri.parse(url), '10.1.1.1',
HttpClientBasicCredentials('user', 'pass'));
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
HttpClientRequest memoryRequest = await client.getUrl(Uri.parse(
'$url=SELECT+TOP+15+IPAddress,+Description,+DNS,+SysName,+Vendor,+Status,+Last Boot,+PercentMemoryUsed,+PercentMemoryAvailable,+MachineType, +TotalMemory+FROM+Orion.Nodes+ORDER+By+PercentMemoryUsed+DESC'));
memoryRequest.headers.set('content-type', 'application/json',);
HttpClientResponse memoryResponse = await memoryRequest.close();
var reply = await memoryResponse.transform(utf8.decoder).join();
var memJasonData = json.decode(reply);
// var memToListData = memJasonData['results'] as List;
List<Results> _getMemoryData1 = memJasonData.map((json) =>
Results.fromJson(json)).toList();
setState(() {
print(_getMemoryData1);
getMemoryData = _getMemoryData1;
print(getMemoryData);
});
// for (var v in memToListData){
// Results memResults = Results(v['iPAddress'], v['description'], v['dNS'], v['sysName'], v['vendor'], v['status'], v['lastBoot'], v['percentMemoryUsed'], v['percentMemoryAvailable'], v['machineType']);
// getMemoryData.add(memResults);
// }
// print(getMemoryData.length);
// print(getMemoryData.runtimeType);
// return getMemoryData;
} '''
class below
below is the class
class Results {
String iPAddress;
String description;
String dNS;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Results(
this.iPAddress,
this.description,
this.dNS,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
);
Results.fromJson(Map<String, dynamic> json) :
iPAddress = json['IPAddress'],
description = json['Description'],
dNS = json['DNS'],
sysName = json['SysName'],
vendor = json['Vendor'],
status = json['Status'],
lastBoot = json['LastBoot'],
percentMemoryUsed = json['PercentMemoryUsed'],
percentMemoryAvailable = json['PercentMemoryAvailable'],
machineType = json['MachineType'];
}
Error
type '(dynamic) => Results' is not a subtype of type '(String, dynamic) =>
MapEntry' of 'transform'
you can copy paste and run full code below
If your json look like this
{"results": [
{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server",
"DNS" : "",
"SysName" :"",
"Vendor":"",
"Status":12,
"LastBoot":"",
"PercentMemoryUsed":123,
"PercentMemoryAvailable": 456,
"MachineType":""
}, {"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server"}]}
code snippet for parse and print
Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');
related class
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Result> results;
Payload({
this.results,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
String ipAddress;
String description;
String dns;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Result({
this.ipAddress,
this.description,
this.dns,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
ipAddress: json["IPAddress"],
description: json["Description"],
dns: json["DNS"] == null ? null : json["DNS"],
sysName: json["SysName"] == null ? null : json["SysName"],
vendor: json["Vendor"] == null ? null : json["Vendor"],
status: json["Status"] == null ? null : json["Status"],
lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
percentMemoryUsed: json["PercentMemoryUsed"] == null ? null : json["PercentMemoryUsed"],
percentMemoryAvailable: json["PercentMemoryAvailable"] == null ? null : json["PercentMemoryAvailable"],
machineType: json["MachineType"] == null ? null : json["MachineType"],
);
Map<String, dynamic> toJson() => {
"IPAddress": ipAddress,
"Description": description,
"DNS": dns == null ? null : dns,
"SysName": sysName == null ? null : sysName,
"Vendor": vendor == null ? null : vendor,
"Status": status == null ? null : status,
"LastBoot": lastBoot == null ? null : lastBoot,
"PercentMemoryUsed": percentMemoryUsed == null ? null : percentMemoryUsed,
"PercentMemoryAvailable": percentMemoryAvailable == null ? null : percentMemoryAvailable,
"MachineType": machineType == null ? null : machineType,
};
}
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Result> results;
Payload({
this.results,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
String ipAddress;
String description;
String dns;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Result({
this.ipAddress,
this.description,
this.dns,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
ipAddress: json["IPAddress"],
description: json["Description"],
dns: json["DNS"] == null ? null : json["DNS"],
sysName: json["SysName"] == null ? null : json["SysName"],
vendor: json["Vendor"] == null ? null : json["Vendor"],
status: json["Status"] == null ? null : json["Status"],
lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
percentMemoryUsed: json["PercentMemoryUsed"] == null
? null
: json["PercentMemoryUsed"],
percentMemoryAvailable: json["PercentMemoryAvailable"] == null
? null
: json["PercentMemoryAvailable"],
machineType: json["MachineType"] == null ? null : json["MachineType"],
);
Map<String, dynamic> toJson() => {
"IPAddress": ipAddress,
"Description": description,
"DNS": dns == null ? null : dns,
"SysName": sysName == null ? null : sysName,
"Vendor": vendor == null ? null : vendor,
"Status": status == null ? null : status,
"LastBoot": lastBoot == null ? null : lastBoot,
"PercentMemoryUsed":
percentMemoryUsed == null ? null : percentMemoryUsed,
"PercentMemoryAvailable":
percentMemoryAvailable == null ? null : percentMemoryAvailable,
"MachineType": machineType == null ? null : machineType,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''
{"results": [
{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server",
"DNS" : "",
"SysName" :"",
"Vendor":"",
"Status":12,
"LastBoot":"",
"PercentMemoryUsed":123,
"PercentMemoryAvailable": 456,
"MachineType":""
}, {"IPAddress":"192.1.1.2","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.3",
"Description":"Windows 2016 Server"}]}
''';
void _incrementCounter() {
Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Output
I/flutter ( 9422): 192.1.1.1
Related
I am using FLutterFlow to build an app and my coding level is beginner. I need to create a valid push data payload structure (JSON) at backend side to pass to app two parameters:
app page (tab) name that should be opened when user taps on push (is called "initialPageName" in code below)
push unique id assigned by backend (is called "pushGUID" in code below)
Below is push handler code that is under the hood of FlutterFlow web app builder, I can not change it. I know it works, because when I use FlutterFlow web push sender and fill in "initial page" and "push GUID" everything works fine. But when I send push from my backend using FCM HTTP API I get only notification itself, data payload with "push GUID" is not handled correctly.
import 'dart:async';
import 'dart:convert';
import 'serialization_util.dart';
import '../backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import '../../index.dart';
import '../../main.dart';
final _handledMessageIds = <String?>{};
class PushNotificationsHandler extends StatefulWidget {
const PushNotificationsHandler({Key? key, required this.child})
: super(key: key);
final Widget child;
#override
_PushNotificationsHandlerState createState() =>
_PushNotificationsHandlerState();
}
class _PushNotificationsHandlerState extends State<PushNotificationsHandler> {
bool _loading = false;
Future handleOpenedPushNotification() async {
if (isWeb) {
return;
}
final notification = await FirebaseMessaging.instance.getInitialMessage();
if (notification != null) {
await _handlePushNotification(notification);
}
FirebaseMessaging.onMessageOpenedApp.listen(_handlePushNotification);
}
Future _handlePushNotification(RemoteMessage message) async {
if (_handledMessageIds.contains(message.messageId)) {
return;
}
_handledMessageIds.add(message.messageId);
if (mounted) {
setState(() => _loading = true);
}
try {
final initialPageName = message.data['initialPageName'] as String;
final initialParameterData = getInitialParameterData(message.data);
final parametersBuilder = parametersBuilderMap[initialPageName];
if (parametersBuilder != null) {
final parameterData = await parametersBuilder(initialParameterData);
context.pushNamed(
initialPageName,
params: parameterData.params,
extra: parameterData.extra,
);
}
} catch (e) {
print('Error: $e');
} finally {
if (mounted) {
setState(() => _loading = false);
}
}
}
#override
void initState() {
super.initState();
handleOpenedPushNotification();
}
#override
Widget build(BuildContext context) => _loading
? Container(
color: Colors.white,
child: Image.asset(
'assets/images/logo.png',
fit: BoxFit.contain,
),
)
: widget.child;
}
class ParameterData {
const ParameterData(
{this.requiredParams = const {}, this.allParams = const {}});
final Map<String, String?> requiredParams;
final Map<String, dynamic> allParams;
Map<String, String> get params => Map.fromEntries(
requiredParams.entries
.where((e) => e.value != null)
.map((e) => MapEntry(e.key, e.value!)),
);
Map<String, dynamic> get extra => Map.fromEntries(
allParams.entries.where((e) => e.value != null),
);
static Future<ParameterData> Function(Map<String, dynamic>) none() =>
(data) async => ParameterData();
}
final parametersBuilderMap =
<String, Future<ParameterData> Function(Map<String, dynamic>)>{
'PhoneAuth': ParameterData.none(),
'smsVerify': (data) async => ParameterData(
allParams: {
'phoneNumber': getParameter<String>(data, 'phoneNumber'),
},
),
'MainPage': (data) async => ParameterData(
allParams: {
'pushGUID': getParameter<String>(data, 'pushGUID'),
},
),
'Campaign': ParameterData.none(),
'LoyaltyPoints': ParameterData.none(),
'OnTheMap': ParameterData.none(),
'NewCollections': ParameterData.none(),
'Notifications': ParameterData.none(),
};
Map<String, dynamic> getInitialParameterData(Map<String, dynamic> data) {
try {
final parameterDataStr = data['parameterData'];
if (parameterDataStr == null ||
parameterDataStr is! String ||
parameterDataStr.isEmpty) {
return {};
}
return jsonDecode(parameterDataStr) as Map<String, dynamic>;
} catch (e) {
print('Error parsing parameter data: $e');
return {};
}
}
My guess looking at the code above is that I should use nested JSON like this:
{
"message":{
"notification":{
"body" : "my body",
"title" : "my title",
},
"data" : {
"initialPage":"mainPage",
"params":[
{"pushGUID":"1231231231"}
]
}
}
}
But as I mentioned my Futter code level is beginner, so please have a look at the handler code and correct my JSON structure, thanks for any advice.
I am trying to parse data from a Rest API inside a Dart/Flutter application.
The JSON contains a field called data at the root, which contains a list of Words.
I want to get a List<ArticalList> from this JSON giving json["data"].map((x) => ArticalList.fromJson(x))
I already have the following code:
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.code,
required this.status,
required this.message,
required this.data,
});
final int code;
final String status;
final String message;
final List<ArticalList> data;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
code: json["code"] ?? 0,
status: json["status"] ?? '',
message: json["message"] ?? '',
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"code": code,
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class ArticalList {
ArticalList({
required this.id,
required this.title,
required this.detail,
required this.image,
});
int id;
String title;
String detail;
String image;
factory ArticalList.fromJson(Map<String, dynamic> json) => ArticalList(
id: json["id"] == null ? 0 : json["id"],
title: json["title"] == null ? '' : json["title"],
detail: json["detail"] == null ? '' : json["detail"],
image: json["image"] ?? 'http://eduteksolutions.in/images/logo.jpeg',
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
"detail": detail == null ? null : detail,
"image": image,
};
}
I think your getting error at
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
I create a function with null safety which accept map and return object list
static List<ArticalList> toListFormMap({
Map? map,
}) {
if (map?.isEmpty ?? true) return [];
List<ArticalList> items = [];
map?.forEach((key, data) {
final ArticalList item = ArticalList.fromJson(data);
items.add(item);
});
return items;
}
and same method which convert map to Map
static Map toMapList(List<ArticalList>? items) {
Map map = {};
items?.forEach((element) {
map[element.id] = element.toJson();
});
return map;
}
for both case it handle null data error and also convert Object List to Map list and Map list to Object list.
I hope it will be helpful.
I have an API that returns JSON with dynamic keys, i.e. the key value changes on every GET request.
Ex: This is the format of the JSON.
I have a book model in dart,
class Book {
String id = "";
String title = "";
Book();
Book.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
}
static List<Book> listFromJson(List<dynamic> json) {
return json.map((val) => Book.fromJson(val)).toList();
}
}
and JSON response,
{
"Recommended For You" : [
{
"id" : "001",
"title" : "title001"
},
...
],
"Thrillers" : [
{
"id" : "005",
"title" : "title005"
},
...
]
}
How to parse this into lists of books according to the genre, given that genres (like Thrillers) can change(i.e. it is dynamic and may change for each user)?
Edit 1
Thrillers and Recommended For You aren't constant, some times it may change to Horror and Romantic or something else. It is dynamic
Edit 2 : The solution
Thanks to #lrn's solution, I came up with a new Class
class Recommendations {
String recommendationType;
List<Book> recommendations;
#override
String toString() {
return 'Recomendations[title: $recommendationType]';
}
Recommendations.fromJson(MapEntry<String, dynamic> json) {
if (json == null) return;
this.recommendationType = json.key;
this.recommendations = Book.listFromJson(json.value);
}
static List<Recommendations> listFromJson(Map<String, dynamic> json) {
return json == null
? List<Recommendations>.empty()
: json.entries
.map((value) => new Recommendations.fromJson(value))
.toList();
}
}
If you don't know the keys, but do know that it's a JSON map where the values are the book lists you're looking for, I'd write:
List<Book> parseCategorizedBooksJson(Map<String, dynamic> json) =>
[for (var books in json.values) ...Book.listFromJson(books)];
or
List<Book> parseCategorizedBooksJson(Map<String, dynamic> json) =>
[for (var books in json.values)
for (var book in books) Book.fromJson(book)];
(which avoids building intermediate lists of books).
With this you simply iterate the values of the outer map, and ignore the keys. JSON maps are just plain Dart Maps and you can access the keys as .keys (and then go trough them without needing to known them ahead of time) and access the values as .values (and completely ignore the keys).
Each value is a list of books, which you can parse using your existing static functions.
To include the genre, you have to say how you want the genre remembered. The simplest is to retain the data as a map:
var categoriedBooks = {for (var genre in json)
genre: Book.listFromJson(json[genre])
};
This builds a map with the same keys (the genres), but where the values are now lists of Books.
Your response model contains two different arrays, recommendedForYou and thrillers. So, you can handle it like this:
// To parse this JSON data, do
//
// final responseModel = responseModelFromJson(jsonString);
import 'dart:convert';
ResponseModel responseModelFromJson(String str) => ResponseModel.fromJson(json.decode(str));
String responseModelToJson(ResponseModel data) => json.encode(data.toJson());
class ResponseModel {
ResponseModel({
this.recommendedForYou,
this.thrillers,
});
List<Book> recommendedForYou;
List<Book> thrillers;
factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(
recommendedForYou: json["Recommended For You"] == null ? null : List<Book>.from(json["Recommended For You"].map((x) => Book.fromJson(x))),
thrillers: json["Thrillers"] == null ? null : List<Book>.from(json["Thrillers"].map((x) => Book.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Recommended For You": recommendedForYou == null ? null : List<dynamic>.from(recommendedForYou.map((x) => x.toJson())),
"Thrillers": thrillers == null ? null : List<dynamic>.from(thrillers.map((x) => x.toJson())),
};
}
class Book {
Book({
this.id,
this.title,
});
String id;
String title;
factory Book.fromJson(Map<String, dynamic> json) => Book(
id: json["id"] == null ? null : json["id"],
title: json["title"] == null ? null : json["title"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
};
}
You can use this site to convert your json to any dart model.
I am a newbie in flutter and I'm trying to create 3 dropdown menus from a json file hosted online. Here is a sample of the json file. This is the link to the json file and this is the model class:
class DropdownModel {
DropdownModel({
this.sports,
this.movies,
this.tv,
});
List<Movie> sports;
List<Movie> movies;
List<Movie> tv;
factory DropdownModel.fromJson(Map<String, dynamic> json) => DropdownModel(
sports: List<Movie>.from(json["sports"].map((x) => Movie.fromJson(x))),
movies: List<Movie>.from(json["movies"].map((x) => Movie.fromJson(x))),
tv: List<Movie>.from(json["tv"].map((x) => Movie.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sports": List<dynamic>.from(sports.map((x) => x.toJson())),
"movies": List<dynamic>.from(movies.map((x) => x.toJson())),
"tv": List<dynamic>.from(tv.map((x) => x.toJson())),
};
}
class Movie {
Movie({
this.id,
this.name,
});
int id;
String name;
factory Movie.fromJson(Map<String, dynamic> json) => Movie(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
How do I go about it?
EDIT
After searching around got a solution I came across this solution which answers my question
An example would be:
// Let's supose you have a variable of the DropdownModel
DropwdownModel model = DropdownModel(...);
// We store the current dropdown value
// Here you can put the default option
// Since you have Movies with id, I would recommend saving
// the movie value as the dropdownValue
String dropdownValue = '';
// For example, let's use the music
#override
Widget build(BuildContext context) {
// We define the dropdown button
return DropdownButton<String>(
// The value is the selected value, you should control the state
value: model.fromNameFromId(dropdownValue),
// The icon to open the dropdown
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
// On changed is the method that it is called when a dropdown option
// is selected
onChanged: (String? newValue) {
// Here we change the state, as I noted before
// The newValue will be a movie id
setState(() {
dropdownValue = newValue!;
});
},
items: model.movies.map<DropdownMenuItem<String>>(
// We have to iterate through all the movies and return
// a list of DropdownMenuItems
(Movie m) {
return DropdownMenuItem<String>(
value: m.id,
// We display the movie name instead of the id
child: Text(m.name),
);
})
.toList(),
);
}
If you want three dropdowns, you would have to create three DropdownButton! You can find more information in the documentation!
i'm confusing with this kind of json.
because i never see someone explain about this kind of json data.
i get my jsondata from a link, and the json data show like this
{
"data": [
{
"jenis_komoditas": "Gabah IR 64 KP",
"harga": "5400",
"satuan": "Kg",
"persen": null,
"perubahan": "0",
"selisi": "0",
"image": "assets\/thumb\/gabah.png"
},
{
"jenis_komoditas": "Gabah IR 64 KG",
"harga": "6200",
"satuan": "Kg",
"persen": null,
"perubahan": "0",
"selisi": "0",
"image": "assets\/thumb\/gabah1.png"
}
]
}
it gets error.
can someone help me how to get the data from first json type?
You can parse your full json string with
Payload payload = payloadFromJson(jsonString);
print('${payload.data[0].jenisKomoditas}');
Related Class
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Datum> data;
Payload({
this.data,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String jenisKomoditas;
String harga;
String satuan;
dynamic persen;
String perubahan;
String selisi;
String image;
Datum({
this.jenisKomoditas,
this.harga,
this.satuan,
this.persen,
this.perubahan,
this.selisi,
this.image,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
jenisKomoditas: json["jenis_komoditas"],
harga: json["harga"],
satuan: json["satuan"],
persen: json["persen"],
perubahan: json["perubahan"],
selisi: json["selisi"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"jenis_komoditas": jenisKomoditas,
"harga": harga,
"satuan": satuan,
"persen": persen,
"perubahan": perubahan,
"selisi": selisi,
"image": image,
};
}
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Datum> data;
Payload({
this.data,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String jenisKomoditas;
String harga;
String satuan;
dynamic persen;
String perubahan;
String selisi;
String image;
Datum({
this.jenisKomoditas,
this.harga,
this.satuan,
this.persen,
this.perubahan,
this.selisi,
this.image,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
jenisKomoditas: json["jenis_komoditas"],
harga: json["harga"],
satuan: json["satuan"],
persen: json["persen"],
perubahan: json["perubahan"],
selisi: json["selisi"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"jenis_komoditas": jenisKomoditas,
"harga": harga,
"satuan": satuan,
"persen": persen,
"perubahan": perubahan,
"selisi": selisi,
"image": image,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''
{
"data": [
{
"jenis_komoditas": "Gabah IR 64 KP",
"harga": "5400",
"satuan": "Kg",
"persen": null,
"perubahan": "0",
"selisi": "0",
"image": "assets\/thumb\/gabah.png"
},
{
"jenis_komoditas": "Gabah IR 64 KG",
"harga": "6200",
"satuan": "Kg",
"persen": null,
"perubahan": "0",
"selisi": "0",
"image": "assets\/thumb\/gabah1.png"
}
]
}
''';
void _incrementCounter() {
Payload payload = payloadFromJson(jsonString);
print('${payload.data[0].jenisKomoditas}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Output
I/flutter (23421): Gabah IR 64 KP
you are getting data in form of json array so you can simply call it iteratively from the object. like this
if you get data in data variable:
final jsondata=json.decode(data);
for (var dataf in jsondata['data']){
print(dataf['jenis_komoditas']);
}