Flutter: How to get data from api and bind in PaginatedDataTable - flutter

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class DataTableDemo extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Service History'),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
PaginatedDataTable(
header: Text('Service Details'),
rowsPerPage: 4,
columns: [
DataColumn(label: Text('SrNo.')),
DataColumn(label: Text('Customer Name')),
DataColumn(label: Text('Mobile Number')),
DataColumn(label: Text('Address')),
DataColumn(label: Text('Company')),
DataColumn(label: Text('Model')),
DataColumn(label: Text('REGNo')),
],
source: _DataSource(context),
),
],
),
);
}
}
fetchSummary() async {
final response = await http.get('https://api');
if (response.statusCode == 200) {
var parsed = json.decode(response.body);
List jsonResponse = parsed["Table"] as List;
return jsonResponse.map((job) => new _Row.fromJson(job)).toList();
} else {
print('Error, Could not load Data.');
throw Exception('Failed to load Data');
}
}
class _Row {
_Row(
this.srNo,
this.customerName,
this.mobileNumber,
this.address,
this.company,
this.model,
this.rEGNo,
);
final int srNo;
final String customerName;
final String mobileNumber;
final String address;
final String company;
final String model;
final String rEGNo;
bool selected = false;
factory _Row.fromJson(Map<String, dynamic> json) {
return _Row(
json['SrNo'],
json['CustomerName'],
json['MobileNumber'],
json['Address'],
json['Company'],
json['Model'],
json['REGNo'],
);
}
}
class _DataSource extends DataTableSource {
_DataSource(this.context) {
_rows =
fetchSummary();
}
final BuildContext context;
List<_Row> _rows;
int _selectedCount = 0;
#override
DataRow getRow(int index) {
assert(index >= 0);
if (index >= _rows.length) return null;
final row = _rows[index];
return DataRow.byIndex(
index: index,
//selected: row.selected,
onSelectChanged: (value) {
if (row.selected != value) {
_selectedCount += value ? 1 : -1;
assert(_selectedCount >= 0);
row.selected = value;
notifyListeners();
}
},
cells: [
DataCell(Text(row.srNo.toString())),
DataCell(Text(row.customerName)),
DataCell(Text(row.mobileNumber)),
DataCell(Text(row.address)),
DataCell(Text(row.company)),
DataCell(Text(row.model)),
DataCell(Text(row.rEGNo)),
],
);
}
#override
int get rowCount => _rows.length;
#override
bool get isRowCountApproximate => false;
#override
int get selectedRowCount => _selectedCount;
}
i have tried this code but getting error when bind data. when i call API and get data (Json format) from server, unable to convert data and got error.how can i convert my data and bind into PaginatedDataTable.
Source Code From: [https://material.io/components/data-tables/flutter#theming-data-tables] .

What you need is a change notifier.
Lets make a quick example.
Here is my model:
{
"id":1,
"name": "John Doe",
"username":"johndoe",
"email":"johndoe#mail.com",
"address":"address",
"phone":"1234567890",
"website":"johndoe.com",
"company":"johndoe pty ltd"
}
then my flutter data model will look something like this:
import 'dart:convert';
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
Next I will create a Data Change Notifier for the UserModel Class:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show PaginatedDataTable;
class UserDataNotifier with ChangeNotifier {
UserDataNotifier() {
fetchData();
}
List<UserModel> get userModel => _userModel;
var _userModel = <UserModel>[]
Future<void> fetchData() async {
_userModel = await Api.fetchData();
notifyListeners();
}
}
Notice that we are using _userModel = await Api.fetchData(); this can be your own implementation for an API. If you need assistance with this, look into Dio for Flutter.
Data is fetched on the init of the ChangeNotifier.
Next we will create a datasource to house all the data:
import 'package:flutter/material.dart';
class UserDataTableSource extends DataTableSource {
UserDataTableSource({
#required List<UserModel> userData,
#required this.onRowSelect,
}) : _userData = userData,
assert(userData != null);
final List<UserModel> _userData;
final OnRowSelect onRowSelect;
#override
DataRow getRow(int index) {
assert(index >= 0);
if (index >= _userData.length) {
return null;
}
final _user = _userData[index];
return DataRow.byIndex(
index: index, // DON'T MISS THIS
cells: <DataCell>[
DataCell(Text('${_user.name}')),
DataCell(Text('${_user.username}')),
DataCell(Text('${_user.email}')),
DataCell(Text('${_user.address}')),
DataCell(Text('${_user.phone}')),
DataCell(Text('${_user.website}')),
DataCell(Text('${_user.company}')),
],
);
}
#override
bool get isRowCountApproximate => false;
#override
int get rowCount => _userData.length;
#override
int get selectedRowCount => 0;
}
Lastly we will use this Change Notifier and DataSource within our Widget:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class DataTableScreen extends StatelessWidget {
const DataTableScreen({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
//
return Stack(
// scrollDirection: Axis.horizontal,
children: [
ChangeNotifierProvider(
create: (_) => UserDataNotifier(),
child: _InternalWidget()
)
],
);
}
}
class _InternalWidget extends StatelessWidget {
const _InternalWidget({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
//
final _provider = context.watch<UserDataNotifier>();
final _model = _provider.userModel;
if (_model.isEmpty) {
return const SizedBox.shrink();
}
final _dtSource = UserDataTableSource(
userData: _model,
);
return PaginatedDataTable(
source: _dtSource,
horizontalMargin: 10,
columnSpacing: 10,
showFirstLastButtons: true,
rowsPerPage: PaginatedDataTable.defaultRowsPerPage,
columns: const [
DataColumn(
label: Text("Name"),
),
DataColumn(
label: Text("User Name"),
),
DataColumn(
label: Text("E-mail"),
),
DataColumn(
label: Text("Address"),
),
DataColumn(
label: Text("Phone"),
),
DataColumn(
label: Text("Website"),
),
DataColumn(
label: Text("Company"),
)
],
);
}
}

Related

Unhandled Exception: Failed host lookup:

I created project to look for sports stadiums in my town. It gets all data from website's Swagger API, data like addresses, price, images and names.
Swagger host: http://admin.sports.com.kg/swagger/
I created ApiRemote to get data from swagger host. It worked perfectly first week, but later it returned exception. Maybe it's because of http.
Terminal returns this error:
E/flutter (26867): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Failed host lookup: 'admin.sports.com.kg'
It says it has an exception in this line:
var responses = await client.get(uri);
import 'dart:async';
import 'dart:convert';
import 'package:untitled/models/post.dart';
import 'package:http/http.dart' as http;
class RemoteService {
Future<List<Result>?> getPosts() async {
List<Result> list;
var client = http.Client();
var uri = Uri.parse('http://admin.sports.com.kg/api/sports_areas');
var responses = await client.get(uri);
if (responses.statusCode == 200) {
final parsed = json.decode(responses.body) as Map<String, dynamic>;
list = parsed['results'].map<Result>((e) =>Result.fromJson(e)).toList();
print(parsed['results']);
// final p = Post.fromJson(parsed);
// list.add(p);
return list;
}
}
}
Post file that contains all data from Swagger
import 'dart:convert';
Post postFromJson(String str) => Post.fromJson(json.decode(str));
String postToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
required this.next,
this.previous,
required this.count,
required this.pageSize,
required this.numPages,
required this.results,
});
int next;
dynamic previous;
int count;
int pageSize;
int numPages;
List<Result> results;
factory Post.fromJson(Map<String, dynamic> json) => Post(
next: json["next"],
previous: json["previous"],
count: json["count"],
pageSize: json["page_size"],
numPages: json["num_pages"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"next": next,
"previous": previous,
"count": count,
"page_size": pageSize,
"num_pages": numPages,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.id,
required this.title,
required this.price,
required this.address,
required this.image,
});
int id;
String title;
int price;
String address;
String image;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
title: json["title"],
price: json["price"],
address: json["address"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"price": price,
"address": address,
"image": image,
};
}
Main Page class
class _HomePageState extends State<HomePage> {
int _selind = 0;
List<Result>? _stadiums;
var isLoaded = false;
#override
void initState() {
super.initState();
getData();
}
void getData() async {
_stadiums = (await RemoteService().getPosts()) as List<Result>?;
if (_stadiums != null) {
setState(() {
isLoaded = true;
});
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.indigo[50],
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 30),
child: Visibility(
visible: isLoaded,
child: ListView.builder(
itemCount: _stadiums?.length,
itemBuilder: (context, index) {
return Column(
// child: _widgetopt.elementAt(_selind),
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: [
Image.network(_stadiums![index].image),
Text('Sportclubs "${_stadiums![index]
.title}"', textDirection: TextDirection.ltr,
style: TextStyle(fontSize: 20,
fontWeight: FontWeight.bold),),
Row(
children: [
Icon(Icons.location_on_outlined,
color: Colors.redAccent, size: 40,),
Text(_stadiums![index].address),
],
)
]
),
),
SizedBox(
height: 10,
),
],
);
}),
replacement: Center(child: CircularProgressIndicator()),
),
),),);
}
}

Getting a getter length is called on Null error when trying to access List on Firebase using flutter

I am trying to retrieve and display a list of items on firebase, I have been able to access everything else on firebase apart from the list itself. I think the issue might be how I am going about retrieving the list because of the method in which it was saved. Here is the order model code
import 'package:butcherbox/models/productsModel.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:meta/meta.dart';
class Order {
Order(
{#required this.items,
//this.theItems,
this.location,
this.orderId,
this.time,
#required this.price});
final List<ProductsModel> items;
final String location;
final int orderId;
final Timestamp time;
final int price;
factory Order.fromMap(Map<String, dynamic> data) {
if (data == null) {
return null;
}
final List<ProductsModel> items = data['items'];
final String location = data['location'];
final int price = data['price'];
final int orderId = data['orderId'];
final Timestamp time = data['time'];
return Order(
items: items,
location: location,
price: price,
orderId: orderId,
time: time,
);
}
Map<String, dynamic> toMap() {
return {
'item': items.map((e) => e.toJson()).toList(),
'location': location,
'orderId': orderId,
'time': time,
'price': price
};
}
}
This is the code to display the data
import 'package:butcherbox/butch_widgets/order_list_tile.dart';
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:butcherbox/services/database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Orders extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.green[200],
title: Text(
'Orders',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.green[900]),
),
),
body: _buildContents(context),
);
}
Widget _buildContents(BuildContext context) {
final database = Provider.of<Database>(context, listen: false);
return StreamBuilder<List<Order>>(
stream: database.ordersStream(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final orders = snapshot.data;
// final children =
// orders.map((order) => Text(order.location)).toList();
final children =
orders.map((order) => OrderListTile(order: order)).toList();
return ListView(children: children);
}
if (snapshot.hasError) {
return Center(child: Text('Some Error Occurred'));
}
return Center(child: CircularProgressIndicator());
});
}
}
This is the widget for the UI
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:flutter/material.dart';
class OrderListTile extends StatelessWidget {
final Order order;
const OrderListTile({Key key, #required this.order}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(
'Order No: ${order.orderId}',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.green[900]),
),
trailing: Text(
'Vendor: ${order.location}',
style: TextStyle(fontSize: 16),
),
subtitle: ListView.builder(
itemCount: order.items.length, <-- This is where the error is
shrinkWrap: true,
itemBuilder: (context, i) {
return Expanded(
child: Column(
children: [
Text('${order.items[i].name}'),
Text('${order.items[i].quantity.toString()}')
],
),
);
}),
isThreeLine: true,
);
}
}
This is the database code
import 'package:butcherbox/models/ordersmodel.dart';
import 'package:butcherbox/services/api_path.dart';
import 'package:meta/meta.dart';
import 'package:butcherbox/services/firestore_service.dart';
abstract class Database {
Future<void> createOrder(Order order);
Stream<List<Order>> ordersStream();
}
String docFromId() => DateTime.now().toIso8601String();
class FireStoreDatabase implements Database {
FireStoreDatabase({#required this.uid}) : assert(uid != null);
final String uid;
final _service = FireStoreService.instance;
Future<void> createOrder(Order order) => _service.setData(
//path: APIPath.order(uid, 'orderdetails'), data: order.toMap());
path: APIPath.order(uid, docFromId()),
data: order.toMap(),
);
Stream<List<Order>> ordersStream() => _service.collectionStream(
path: APIPath.orders(uid), builder: (data) => Order.fromMap(data));
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
class FireStoreService {
FireStoreService._();
static final instance = FireStoreService._();
Future<void> setData({String path, Map<String, dynamic> data}) async {
final reference = FirebaseFirestore.instance.doc(path);
print('$path: $data');
await reference.set(data);
}
Stream<List<T>> collectionStream<T>({
#required String path,
#required T Function(Map<String, dynamic> data) builder,
}) {
final reference = FirebaseFirestore.instance.collection(path);
final snapshots = reference.snapshots();
return snapshots.map((snapshot) => snapshot.docs
.map(
(snapshot) => builder(snapshot.data()),
)
.toList());
}
}
Yes actually you are right, so here are some keypoints,
Stream<List<Order>> ordersStream() => _service.collectionStream(
path: APIPath.orders(uid), builder: (data) =>
// This is supposed to be a list of Orders.
Order.fromMap(data));
You can try printing the data here so you see what I am talking about(it would be a List and not a singular object).

My app doesn't recognize data from model file

Hello this is my model file;
// To parse this JSON data, do
//
// final hisselist = hisselistFromJson(jsonString);
import 'dart:convert';
Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str));
String hisselistToJson(Hisselist data) => json.encode(data.toJson());
class Hisselist {
Hisselist({
required this.success,
required this.result,
});
bool success;
List<dynamic> result;
factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
success: json["success"],
result: List<dynamic>.from(json["result"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"success": success,
"result": List<dynamic>.from(result.map((x) => x)),
};
}
class ResultClass {
ResultClass({
required this.rate,
required this.lastprice,
required this.lastpricestr,
required this.hacim,
required this.hacimstr,
required this.text,
required this.code,
});
double rate;
double lastprice;
String lastpricestr;
double hacim;
String hacimstr;
String text;
String code;
factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
rate: json["rate"].toDouble(),
lastprice: json["lastprice"].toDouble(),
lastpricestr: json["lastpricestr"],
hacim: json["hacim"].toDouble(),
hacimstr: json["hacimstr"],
text: json["text"],
code: json["code"],
);
Map<String, dynamic> toJson() => {
"rate": rate,
"lastprice": lastprice,
"lastpricestr": lastpricestr,
"hacim": hacim,
"hacimstr": hacimstr,
"text": text,
"code": code,
};
}
And this is my file where i call API
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:easy_localization/easy_localization.dart';
import '../models/apis/hisselist.dart';
class Stocks extends StatefulWidget {
Stocks({Key? key}) : super(key: key);
#override
_StocksState createState() => _StocksState();
}
class _StocksState extends State<Stocks> with AutomaticKeepAliveClientMixin {
ScrollController? controller;
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
var counter;
var hisseResult;
Future callHisse() async {
try{
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'apikey xxx'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = 200;
hisseResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
callHisse();
}
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
centerTitle: false,
automaticallyImplyLeading: false,
title: Text(
'Hisseler'
).tr(),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: counter != null ?
ListView.builder(
itemCount: counter,
itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(hisseResult.data[index].code),
subtitle: Text(hisseResult.data[index].text),
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
#override
bool get wantKeepAlive => true;
}
And I'm getting this error?
What's wrong with it?
Thanks for your help
Hisselist class has only two properties, success and result.
This line of code returns result that is Hisselist type:
var result = hisselistFromJson(response.body);
You should avoid using var type here and set Hisselist instead:
Hisselist? result = hisselistFromJson(response.body);
hisseResult variable is also Hisselist type so you can only use success and result properties, there is no data property defined in Hisselist class.
Hisselist? hisseResult instead od var type.
title: Text(hisseResult?.result[index].code ?? ""),
subtitle: Text(hisseResult?.result[index].text ?? ""),
There is no field as it described on your model class
I think you want result.
Try var hisseResult; to Hisselist? hisseResult;
title: Text(hisseResult?.result[index].code??""),
hisseResult.result[index] replace for hisseResult.data[index]
itemCount: hisseResult.result.length replace for itemCount: counter,

load data using provider call while navigating to the screen

I have managed to load data from odoo db, the data can be loaded at first call but after updating or creatinig a new customer in server side odoo database nothing happens in my flutter app. the data not loaded in customer screen
i tried to call the provider in initState , setState but nothing worked for me.
customer model
class Customer {
int id;
String name;
Customer({
required this.id,
required this.name,
});
factory Customer.fromJson(Map<dynamic, dynamic> json) => Customer(
name: json["name"],
id: json["id"],
);
Map<dynamic, dynamic> toJson() => {
"name": name,
"id": id,
};
}
Customer provider
class CustomerProvider with ChangeNotifier {
CustomerProvider() {
loadCustomers().then((customers) {
_customers = customers;
notifyListeners();
});
}
List<Customer> _customers = [];
List<Customer> get customers => _customers;
Future getCustomer() async {
notifyListeners();
final client = OdooClient('http://localhost:8050');
await client.authenticate('odoo', 'admin', 'admin');
var res = await client.callKw({
'model': 'res.partner',
'method': 'search_read',
'args': [],
'kwargs': {
'context': {'bin_size': true},
// 'domain': [
// ['id','=',10]
// ],
'fields': ['name'],
},
});
return res;
}
Future loadCustomers() async {
notifyListeners();
final data = await getCustomer();
_customers = ((data as List).map((i) => Customer.fromJson(i)).toList());
return _customers;
}
}
Customer screen
class CustomerPage extends StatefulWidget {
final bool? isMultiSelection;
final List<Customer> customers;
const CustomerPage({
Key? key,
this.isMultiSelection = false,
this.customers = const [],
}) : super(key: key);
#override
_CustomerPageState createState() => _CustomerPageState();
}
class _CustomerPageState extends State<CustomerPage> {
String text = '';
bool loading = false;
List<Customer>? csm;
#override
void initState() {
super.initState();
}
bool containsSearchText(Customer customer) {
final name = customer.name;
final textLower = text.toLowerCase();
final customerLower = name.toLowerCase();
return customerLower.contains(textLower);
}
#override
Widget build(BuildContext context) {
var provider = Provider.of<CustomerProvider>(context, listen: false);
var allcustomers = provider.customers;
var customers = allcustomers.where(containsSearchText).toList();
return ChangeNotifierProvider.value(
value: CustomerProvider(),
child: loading ? const Loading() : Scaffold(
appBar: AppBar(
title: const Text('Selectionner un client'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(60),
child: SearchWidget(
text:text,
hintText: 'Rechercher',
onChanged: (text) => setState(() => this.text = text),
)),
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[Color(0xffC71C24), Color(0xffFDBA45)]),
),
),
),
body: customers.isEmpty
// ? const Center(child: CircularProgressIndicator(color: Color(0xffFDBA45),),)
? const Loading()
: ListView(
children: customers.map((customer) {
return CustomerListTileWidget(
customer: customer,
isSelected: false,
onSelectedCustomer: selectCustomer
);
}).toList(),
),
)
);
}

How can I get string value from API in flutter?

I am trying to get string value from the API to the list in a flutter.
Each time I try to get the list there is an exception "Unhandled Exception: type 'String' is not a subtype of type 'Map'"
the data I have is in the format given below:
{
"status": 1,
"data": [
"Chapter 1",
"Chapter 2",
]
}
Use this response class to load response and access all the variables.
class ResponseData {
String status;
List<String> data;
ResponseData({
this.status,
this.data,
});
factory ResponseData.fromJson(Map<String, dynamic> json) => ResponseData(
status: json["status"],
data: List<String>.from(json["data"].map((x) => x)),
);
}
Add our response json to ResponseData class
ResponseData responseDataFromJson(String responseFromServiceCall) => ResponseData.fromJson(json.decode(responseFromServiceCall));
From the above mentioned json i have created a sample json for ListView :
{
"status": 1,
"data": [
"Chapter 1",
"Chapter 2"
]
}
Creating a model class from the json :
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
int status;
List<String> data;
Data({
this.status,
this.data,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
status: json["status"],
data: List<String>.from(json["data"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x)),
};
}
Parsing data and then rendering it on ui :
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dummy.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<String> dataList = List();
bool _isLoading = false;
#override
void initState() {
super.initState();
loadYourData();
}
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
loadYourData() async {
setState(() {
_isLoading = true;
});
String jsonString = await loadFromAssets();
final data = dataFromJson(jsonString);
// here you get the complete object
dataList = data.data;
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(dataList[index]),
),
],
),
);
},
),
),
),
);
}
}
Following is the parse.json file :
And below is the pubspec file where you need to define the json folder :
Let me know if it works.