Last active
June 17, 2022 19:01
-
-
Save ayoubzulfiqar/416faa4f08e247337e8e77763adb58cd to your computer and use it in GitHub Desktop.
accessing data from json in flutter include both local and online method. usually local json consider as a demo data model for project.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// demo json file. --------Note the image is from local assest file. so use Image.assest method in dart to access. for network use Image.network in flutter | |
// place json file outside of lib folder | |
[ | |
{ | |
"id": 0, | |
"name": "NexMart - Casual Sneakers", | |
"category": "NOP", | |
"imageUrl": "img/header_onboarding/first_header.png", | |
"oldPrice": "1899", | |
"price": "799" | |
}, | |
{ | |
"id": 1, | |
"name": "Asian - Men Bouncer", | |
"category": "Men", | |
"oldPrice": "999", | |
"imageUrl": "img/header_onboarding/headerTwo.jpg", | |
"price": "719" | |
}, | |
{ | |
"id": 2, | |
"name": "Sparx", | |
"category": "Men", | |
"imageUrl": "img/header_onboarding/headerThree.jpg", | |
"oldPrice": "1349", | |
"price": "944" | |
}, | |
{ | |
"id": 3, | |
"name": "Ethics", | |
"category": "Men", | |
"imageUrl": "img/header_onboarding/headerFour.jpg", | |
"oldPrice": "999", | |
"price": "469" | |
} | |
] | |
// creating model for our local json. -------Note creating model is essential both for local as well as online josn file | |
// --- some useful website to create models | |
// https://javiercbk.github.io/json_to_dart/ | |
// https://quicktype.io/ | |
class Product { | |
Product({ | |
this.id, | |
this.name, | |
this.category, | |
this.imageUrl, | |
this.oldPrice, | |
this.price, | |
}); | |
int? id; | |
String? name; | |
String? category; | |
String? imageUrl; | |
String? oldPrice; | |
String? price; | |
factory Product.fromJson(Map<String, dynamic> json) => Product( | |
id: json["id"], | |
name: json["name"], | |
category: json["category"], | |
imageUrl: json["imageUrl"], | |
oldPrice: json["oldPrice"], | |
price: json["price"], | |
); | |
Map<String, dynamic> toJson() => { | |
"id": id, | |
"name": name, | |
"category": category, | |
"imageUrl": imageUrl, | |
"oldPrice": oldPrice, | |
"price": price, | |
}; | |
} | |
// parsing method -- with futureBuilder | |
Future<List<Product>> readJsonData() async { | |
// database/produc.json ----------- this is location of the json file also add into pubspec.yaml file location | |
// assets: | |
// - database/produc.json | |
final jsonData = await rootBundle.loadString('database/produc.json'); | |
final list = json.decode(jsonData) as List<dynamic>; | |
return list.map((e) => Product.fromJson(e)).toList(); | |
// -------- without future builder access it as in Column | |
List<Product> product; | |
// Flutter Widget access method | |
FutureBuilder( | |
future: readJsonData(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
if (snapshot.hasError) { | |
return Center(child: Text('${snapshot.error}')); | |
} else if (snapshot.hasData) { | |
var product = snapshot.data as List<Product>; | |
return ListView.builder( | |
itemCount: product.length, | |
itemBuilder: (context, index) { | |
return Container( | |
width: 100, | |
height: 100, | |
// use network if thee= image inside json is from internet | |
child: Image.asset(product[index].imageUrl.toString())); | |
}); | |
} | |
return const Center(child: CircularProgressIndicator()); | |
}), | |
// =====================================================// | |
// list array of Objects on JSON using stateful widget | |
// example JSON | |
{ | |
"items": [ | |
{ | |
"id": "p1", | |
"name": "Item 1", | |
"description": "Description 1" | |
}, | |
{ | |
"id": "p2", | |
"name": "Item 2", | |
"description": "Description 2" | |
}, | |
{ | |
"id": "p3", | |
"name": "Item 3", | |
"description": "Description 3" | |
} | |
] | |
} | |
// add JSon file in assests folder | |
flutter: | |
assets: | |
- assets/sample.json | |
// in Widget | |
class HomePage extends StatefulWidget { | |
const HomePage({Key? key}) : super(key: key); | |
@override | |
_HomePageState createState() => _HomePageState(); | |
} | |
class _HomePageState extends State<HomePage> { | |
List _items = []; | |
// Fetch content from the json file | |
Future<void> readJson() async { | |
final String response = await rootBundle.loadString('assets/sample.json'); | |
final data = await json.decode(response); | |
setState(() { | |
_items = data["items"]; // array name in JSON file | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: FutureBuilder( | |
future: loadJson(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
if (snapshot.hasError) { | |
return Center(child: Text("${snapshot.error}")); | |
} else if (snapshot.hasData) { | |
return ListView.builder( | |
itemCount: items.length, | |
itemBuilder: (context, index) { | |
return Column( | |
children: [ | |
Text(items[index]["id"].toString()), // "id" should be samee as in JSON file | |
Text(items[index]["name"].toString()), // "name" should be samee as in JSON file | |
Text(items[index]["description"].toString()), // "description" should be samee as in JSON file | |
], | |
); | |
}); | |
} | |
return Center( | |
child: CircularProgressIndicator(), | |
); | |
}), | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment