Skip to content

Instantly share code, notes, and snippets.

@lbarqueira
Last active September 21, 2020 16:50
Show Gist options
  • Save lbarqueira/3a625587312b714f33b09fd21c682a03 to your computer and use it in GitHub Desktop.
Save lbarqueira/3a625587312b714f33b09fd21c682a03 to your computer and use it in GitHub Desktop.
import 'dart:convert';
// article - How to parde Json in Flutter
// https://www.filledstacks.com/snippet/how-to-parse-json-in-flutter/
void main() {
var jsonData = '{"name" : "Dane", "alias" : "FilledStacks"}';
print(jsonData);
var parsedJson = json.decode(jsonData);
print(parsedJson);
print('${parsedJson.runtimeType} : $parsedJson');
// Direct Parsing and Usage
var name = parsedJson['name'];
var alias = parsedJson['alias'];
print('$name is $alias');
// Parse Into Object
// Instead of using the parsed data directly it's common practice under
// programmers to put this data into a class that models your data for you.
// This is commonly done through a named constructor in Dart. Let's put our test
// data into a model. We'll define the model in the basic way first, then get to
// the named constructor.
// var user = User(parsedJson);
// print('${user.name} is ${user.alias}');
var user = User.fromJson(parsedJson);
print('${user.name} is ${user.alias}');
}
//class User {
// String name;
// String alias;
// User(Map<String, dynamic> data) {
// name = data['name'];
// alias = data['alias'];
// }
//}
// The above way would be fine, but having only that one constructor limits you and does not
// leave your model open for extension. You'll have to modify it to get any other functionality
// into it. Instead the common practice is to have a constructor that sets all the properties
// for you and use a named constructor to create a model explicitly using outside data.
// https://javiercbk.github.io/json_to_dart/
class User {
String name;
String alias;
User(Map<String, dynamic> data) {
name = data['name'];
alias = data['alias'];
}
// named constructor
User.fromJson(Map<String, dynamic> data)
: name = data['name'],
alias = data['alias'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment