I am familiar with creating ListView from array of string but need help using JSON data
I need to create a flutter list view having cards from following JSON data such that, on card only name field is visible whereas, when we click on card both the id and name should be visible on new page.
How to attach a JSON Object to clickable card?
{
"data": [
{
"id": 111,
"name": "abc"
},
{
"id": 222,
"name": "pqr"
},
{
"id": 333,
"name": "abc"
}
]
}
Take the fetched JSON and put it in a map. I created a class to handle it easily (add the fetch data function). Take the array data and put them in a List.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class Data {
Map fetched_data = {
"data": [
{"id": 111, "name": "abc"},
{"id": 222, "name": "pqr"},
{"id": 333, "name": "abc"}
]
};
List _data;
//function to fetch the data
Data() {
_data = fetched_data["data"];
}
int getId(int index) {
return _data[index]["id"];
}
String getName(int index) {
return _data[index]["name"];
}
int getLength() {
return _data.length;
}
}
class _HomeState extends State<Home> {
Data _data = new Data();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.blueGrey,
body: ListView.builder(
padding: const EdgeInsets.all(5.5),
itemCount: _data.getLength(),
itemBuilder: _itemBuilder,
),
),
);
}
Widget _itemBuilder(BuildContext context, int index) {
return InkWell(
child: Card(
child: Center(
child: Text(
"${_data.getName(index)}",
style: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.orange,
),
),
),
),
onTap: () => MaterialPageRoute(
builder: (context) =>
SecondRoute(id: _data.getId(index), name: _data.getName(index))),
);
}
}
Step 1
Create your model, put this json here: https://javiercbk.github.io/json_to_dart/
{
"id": 111,
"name": "abc"
}
Then put the model in you project
Step 2
Convert your data to a list of models
List<YOURMODEL> models = data.map((Map item)=> YOURMODEL.fromJson(item)).toList();
Step 3
Create your list view widget with this list
ListView.builder(
itemCount: models.length,
itemBuilder: (context, index) {
return Card(child:Text(models[index].name));
},
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With