how to pass array of data from API into graph in flutter? - android

I have an issue while integrating an array of data from API into my graph, I have tried all other methods but I don't find any solution. How to Use model class to get API data and integrate it into a graph.
import 'dart:convert';
import 'package:chartapp/network/network_helper.dart';
import 'package:chartapp/src/Bar_Chart/bar_model.dart';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:http/http.dart' as http;
import 'gender_model.dart';
class NetworkHelper {
Future<http.Response> post(String endpoint) async {
var url = Uri.parse(endpoint);
var response = await http.post(url, headers: {
'Authorization':
'token',
'Cookie': ''
});
return response;
}
}
class BarChartAPI extends StatefulWidget {
const BarChartAPI({Key? key}) : super(key: key);
#override
State<BarChartAPI> createState() => _BarChartAPIState();
}
class _BarChartAPIState extends State<BarChartAPI> {
List<Graphmodel> graph = [];
bool loading = true;
NetworkHelper _networkHelper = NetworkHelper();
#override
void initState() {
super.initState();
getData();
}
void getData() async {
var response = await _networkHelper.post(
"*********************************");
final tempdata = json.decode(response.body)['result']["meter"]
["performance"]["growth"]["graph-data"];
List data = tempdata
.map((e) => Graphmodel(name: e['name'], value: e['value']))
.toList();
print(tempdata);
print(data);
setState(() {
graph = data as List<Graphmodel>;
loading = false;
});
}
List<charts.Series<Graphmodel, String>> _createSampleData() {
return [
charts.Series<Graphmodel, String>(
data: graph ,
id: 'graph_data',
colorFn: (_, __) => charts.MaterialPalette.teal.shadeDefault,
domainFn: (Graphmodel graphmodel, _) => graphmodel.name,
measureFn: (Graphmodel graphmodel, _) => graphmodel.value,
)
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Graph"),
),
body: Center(
child: loading
? CircularProgressIndicator()
: Container(
height: 300,
child: charts.BarChart(
_createSampleData(),
animate: true,
),
),
),
);
}
}
This is my console response
[1]: https://i.stack.imgur.com/Hkomh.png
The following is my class model
import 'dart:convert';
List<Graphmodel> graphmodelFromJson(String str) =>
List<Graphmodel>.from(json.decode(str).map((x) => Graphmodel.fromJson(x)));
String graphmodelToJson(List<Graphmodel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Graphmodel {
Graphmodel({
required this.name,
required this.value,
});
String name;
int value;
factory Graphmodel.fromJson(Map<String, dynamic> json) => Graphmodel(
name: json["name"],
value: json["value"],
);
Map<String, dynamic> toJson() => {
"name": name,
"value": value,
};
}

Related

asynchronous suspension after adding ChangeNotifierProxyProvider to my MutiProviders

I am passing the authentication token from Auth.dart file to Products.dart file to enable the app to fetch the Products in my database but the app is not able to fetch those,
I am very new to flutter any help would be appreciated
Thank you
here is my Auth.dart file
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import '../models/http_exceptions.dart';
class Auth with ChangeNotifier {
String _token;
DateTime _expiryDate;
String _userId;
bool get isAuth {
return token != null;
}
String get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
Future<void> _authenticate(
String email, String password, String urlSegment) async {
final url = Uri.parse(
'https://identitytoolkit.googleapis.com/v1/accounts:$urlSegment?key=<key>',
);
try {
final response = await http.post(
url,
body: json.encode(
{
'email': email,
'password': password,
'returnSecureToken': true,
},
),
);
final responseData = json.decode(response.body);
if (responseData['error'] != null) {
throw HttpEception(responseData['error']['message']);
}
_token = responseData['idToken'];
_userId = responseData['localId'];
_expiryDate = DateTime.now().add(
Duration(
seconds: int.parse(responseData['expiresIn']),
),
);
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> signup(String email, String password) async {
return _authenticate(email, password, 'signUp');
}
Future<void> login(String email, String password) async {
return _authenticate(email, password, 'signInWithPassword');
}
}
Here is my Products.dart file, which has the Product class which is
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shop_app/models/http_exceptions.dart';
class Product with ChangeNotifier {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
#required this.id,
#required this.title,
#required this.description,
#required this.price,
#required this.imageUrl,
this.isFavorite = false,
});
Future<void> toggleFavoriteStatus() async {
final url = Uri.https(
'<confedential>.firebaseio.com',
'/products/$id.json',
);
final oldStatus = isFavorite;
isFavorite = !isFavorite;
notifyListeners();
final response = await http.patch(
url,
body: json.encode(
{
'isFavorite': isFavorite,
},
),
);
if (response.statusCode >= 400) {
isFavorite = oldStatus;
notifyListeners();
throw HttpEception('Could Not Change To Favourite');
}
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shop_app/models/http_exceptions.dart';
import './product.dart';
class Products with ChangeNotifier {
List<Product> _items = [];
final String authToken;
Products(this.authToken,this._items);
List<Product> get items {
return [..._items];
}
List<Product> get favoriteItems {
return _items.where((prodItem) => prodItem.isFavorite).toList();
}
Product findById(String id) {
return _items.firstWhere((prod) => prod.id == id);
}
Future<void> fetchAndSetProducts() async {
final url = Uri.https(
'<details>.firebaseio.com',
'/products.json?auth=$authToken',
);
try {
final response = await http.get(url);
// print(json.decode(response.body));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
final List<Product> loadedProducts = [];
extractedData.forEach((productId, productData) {
loadedProducts.add(
Product(
id: productId,
title: productData['title'],
description: productData['description'],
price: productData['price'],
isFavorite: productData['isFavourite'],
imageUrl: productData['imageUrl'],
),
);
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> addProduct(Product product) async {
var url = Uri.https(
'<details>.firebaseio.com',
'/products.json',
);
try {
final response = await http.post(
url,
body: json.encode(
{
'title': product.title,
'description': product.description,
'imageUrl': product.imageUrl,
'price': product.price,
'isFavourite': product.isFavorite,
},
),
);
final newProduct = Product(
title: product.title,
description: product.description,
price: product.price,
imageUrl: product.imageUrl,
id: json.decode(response.body)['name'],
);
_items.add(newProduct);
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> updateProduct(String id, Product newProduct) async {
final prodIndex = _items.indexWhere((prod) => prod.id == id);
if (prodIndex >= 0) {
final url = Uri.https(
'<details>.firebaseio.com',
'/products/$id.json',
);
http.patch(
url,
body: json.encode(
{
'title': newProduct.title,
'description': newProduct.description,
'imageUrl': newProduct.imageUrl,
'price': newProduct.price,
},
),
);
_items[prodIndex] = newProduct;
notifyListeners();
} else {
print('...');
}
}
Future<void> deleteProduct(String id) async {
final url = Uri.https(
'<details>.firebaseio.com',
'/products/$id.json',
);
final exisitingProductIndex = _items.indexWhere((prod) => prod.id == id);
var exisitingProduct = _items[exisitingProductIndex];
_items.removeAt(exisitingProductIndex);
notifyListeners();
final response = await http.delete(url);
if (response.statusCode >= 400) {
_items.insert(exisitingProductIndex, exisitingProduct);
notifyListeners();
throw HttpEception('Could Not Delete Product.');
}
exisitingProduct = null;
}
}
And finally the main.dart file which uses all this stuff
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './providers/auth.dart';
import './screens/cart_screen.dart';
import './screens/products_overview_screen.dart';
import './screens/product_detail_screen.dart';
import './providers/products.dart';
import './providers/cart.dart';
import './providers/orders.dart';
import './screens/orders_screen.dart';
import './screens/user_products_screen.dart';
import './screens/edit_product_screen.dart';
import './screens/auth_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
// Defining these providers for lisening to changes in the data
providers: [
ChangeNotifierProvider.value(
value: Auth(),
),
// First parameter is the type of data that we depened on and second is the data that we arre passing
ChangeNotifierProxyProvider<Auth, Products>(
update: (ctx, auth, previousProducts) => Products(
auth.token,
previousProducts == null ? [] : previousProducts.items,
),
),
ChangeNotifierProvider.value(
value: Cart(),
),
ChangeNotifierProvider.value(
value: Orders(),
),
],
child: Consumer<Auth>(
builder: (context, auth, _) => MaterialApp(
title: 'MyShop',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.deepOrange,
fontFamily: 'Lato',
),
// home: ProductsOverviewScreen(),
home: auth.isAuth ? ProductsOverviewScreen() : AuthScreen(),
routes: {
ProductDetailScreen.routeName: (ctx) => ProductDetailScreen(),
CartScreen.routeName: (ctx) => CartScreen(),
OrdersScreen.routeName: (ctx) => OrdersScreen(),
UserProductsScreen.routeName: (ctx) => UserProductsScreen(),
EditProductScreen.routeName: (ctx) => EditProductScreen(),
},
),
),
);
}
}
Just added create into ChangeNotifierProxyProvider
ChangeNotifierProxyProvider<Auth, Products>(
create: (_)=>Products('',[]),
update: (ctx, auth, previousProducts) => Products(
auth.token,
previousProducts == null ? [] : previousProducts.items,
),
),
and changed the url string in Products.dart file
Uri url = Uri.parse(
'https://<some_details>.firebaseio.com/products.json?auth=$authToken');

Error: Could not find the correct Provider<AuthState> above this AuthPage Widget

ERROR:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ProviderNotFoundException was thrown building AuthPage(dirty, state:
_AuthPageState#7ac1c):
Error: Could not find the correct Provider above this AuthPage Widget
This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:
You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.
The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
You used a BuildContext that is an ancestor of the provider you are trying to read.
Make sure that AuthPage is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using builder like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
My Code:
AuthPage.dart:-
import 'package:first_app/pages/auth/bloc/auth_state.dart';
import 'package:first_app/pages/auth/widgets/auth_button.dart';
import 'package:first_app/pages/auth/widgets/otp_page.dart';
import 'package:first_app/pages/auth/widgets/phone_page.dart';
import 'package:first_app/pages/auth/widgets/set_up_account.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
class AuthPage extends StatefulWidget {
final int page;
final String? uid;
const AuthPage({
Key? key,
this.page = 0,
this.uid,
}) : super(key: key);
#override
_AuthPageState createState() => _AuthPageState();
}
class _AuthPageState extends State<AuthPage> {
#override
Widget build(BuildContext context) {
final state = Provider.of<AuthState>(context);
final screenSize = MediaQuery.of(context).size;
return
Builder(builder: (context) {
return Stack(
children: [
Container(
height: screenSize.height,
width: screenSize.width,
color: Colors.white,
child: PageView(
controller: state.controller,
onPageChanged: state.onPageChanged,
physics: NeverScrollableScrollPhysics(),
children: [
PhonePage(),
OtpPage(),
SetUpAccount(),
],
),
),
AuthButton(),
],
);
});
}
}
class AuthPageWidget extends StatelessWidget {
final int page;
final String? uid;
const AuthPageWidget({
Key? key,
required this.page,
this.uid,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final state = AuthState(page, uid ?? '');
return ChangeNotifierProvider(
create: (_) => state,
child: ChangeNotifierProvider.value(
value: state,
child: AuthPage(page: page, uid: uid),
),
);
}
}
AuthState.dart
import 'dart:async';
import 'package:first_app/models/user.dart';
import 'package:first_app/repositories/user_repository.dart';
import 'package:first_app/services/auth.dart';
import 'package:first_app/services/map_services.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
enum PhoneAuthState { initial, success, loading, codeSent, error }
/*part of 'auth_bloc.dart';
abstract class AuthState extends Equatable {
const AuthState();
#override
List<Object> get props => [];
}*/
class AuthState extends ChangeNotifier {
final authService = AuthService.instance;
final userRepo = UserRepository.instance;
PhoneAuthState _phoneAuthState = PhoneAuthState.initial;
String verificationId = '';
TextEditingController phoneController = TextEditingController();
TextEditingController otpController = TextEditingController();
TextEditingController firstNameController = TextEditingController();
TextEditingController lastNameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController licensePlateController = TextEditingController();
TextEditingController vehicleColorController = TextEditingController();
TextEditingController vehicleTypeController = TextEditingController();
TextEditingController vehicleManufacturersController = TextEditingController();
Roles role = Roles.passenger;
PageController? controller;
int pageIndex = 0;
String uid = '';
int timeOut = 30;
bool get isRoleDriver => role == Roles.driver;
AuthState(int page, String uid) {
this.uid = uid;
controller = PageController(initialPage: page);
pageIndex = page;
notifyListeners();
siginCurrentUser();
}
PhoneAuthState get phoneAuthState => _phoneAuthState;
set changeRoleState(int value) {
role = Roles.values[value];
notifyListeners();
}
set phoneAuthStateChange(PhoneAuthState phoneAuthState) {
_phoneAuthState = phoneAuthState;
notifyListeners();
}
void animateToNextPage(int page) {
controller!.animateToPage(page, duration: Duration(milliseconds: 400), curve: Curves.easeIn);
pageIndex = page;
notifyListeners();
}
void onPageChanged(int value) {
pageIndex = value;
notifyListeners();
}
Future<void> signUp() async {
phoneAuthStateChange = PhoneAuthState.loading;
final address = await MapService.instance?.getCurrentPosition();
try {
final user = User(
uid: uid,
isActive: true,
firstname: firstNameController.text,
lastname: lastNameController.text,
email: emailController.text,
createdAt: DateTime.now(),
isVerified: true,
licensePlate: licensePlateController.text,
phone: "234${phoneController.text}",
vehicleType: vehicleTypeController.text,
vehicleColor: vehicleColorController.text,
vehicleManufacturer: vehicleManufacturersController.text,
role: role,
latlng: address?.latLng,
);
await userRepo.setUpAccount(user);
phoneAuthStateChange = PhoneAuthState.success;
} on FirebaseException catch (e) {
print(e.message);
phoneAuthStateChange = PhoneAuthState.error;
}
}
Future<void> phoneNumberVerification(String phone) async {
await AuthService.instance!.verifyPhoneSendOtp(phone, completed: (credential) async {
if (credential.smsCode != null && credential.verificationId != null) {
verificationId = credential.verificationId ?? '';
notifyListeners();
await verifyAndLogin(credential.verificationId!, credential.smsCode!, phoneController.text);
}
}, failed: (error) {
phoneAuthStateChange = PhoneAuthState.error;
}, codeSent: (String id, int? token) {
verificationId = id;
notifyListeners();
phoneAuthStateChange = PhoneAuthState.codeSent;
codeSentEvent();
print('code sent $id');
}, codeAutoRetrievalTimeout: (id) {
verificationId = id;
notifyListeners();
phoneAuthStateChange = PhoneAuthState.codeSent;
animateToNextPage(1);
print('timeout $id');
});
animateToNextPage(1);
notifyListeners();
}
Future<void> verifyAndLogin(String verificationId, String smsCode, String phone) async {
phoneAuthStateChange = PhoneAuthState.loading;
final uid = await authService?.verifyAndLogin(verificationId, smsCode, phone);
await userRepo.getUser(uid);
this.uid = uid ?? '';
animateToNextPage(2);
notifyListeners();
phoneAuthStateChange = PhoneAuthState.success;
print('completed');
}
Future<void> siginCurrentUser() async {
await userRepo.signInCurrentUser();
}
Future<void> codeSentEvent() async {
animateToNextPage(1);
_startCountDown();
}
void _startCountDown() {
Timer.periodic(Duration(seconds: 1), (timer) {
if (timer.tick > 30) {
timer.cancel();
} else {
--timeOut;
}
notifyListeners();
});
}
}
main.dart
import 'package:first_app/pages/home/home.dart';
import 'package:first_app/repositories/user_repository.dart';
import 'package:first_app/ui/theme.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
UserRepository.instance.signInCurrentUser();
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BrilliantDrive',
theme: CityTheme.theme,
home: HomePage(),
);
}
}
Initialize your provider 1st. Refer this https://stackoverflow.com/a/68418866/16467763.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider<AuthState>(
create: (context) => AuthState(),
),
],
child: MyApp(),
),
);
}
class AuthPageWidget extends StatelessWidget {
final int page;
final String? uid;
const AuthPageWidget({
Key? key,
required this.page,
this.uid,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final state = AuthState(page, uid ?? '');
return ChangeNotifierProvider(
create: (_) => state,
child: ChangeNotifierProvider.value(
value: state,
child: AuthPage(page: page, uid: uid),
),
);
}
}
You should move the ChangeNotifierProvider to your main.dart like this
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
final state = AuthState(page, uid ?? '');
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: ChangeNotifierProvider(
create: (_) => state,
child: AuthPage(page: page, uid: uid),
),
),
);
}
OR
class SomeWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: ChangeNotifierProvider(
create: (_) => state,
child: ChangeNotifierProvider.value(
value: state,
child: AuthPage(page: page, uid: uid),
),
)
),
);
}
}

In FLutter trying to get JSON had this problem: [ LateInitializationError: Field '_userData#577066488' has not been initialized]

I am trying to show the JSON data from a URL to my Flutter application and haven't found any solution yet. because i have the error:
[LateInitializationError: Field '_userData#577066488' has not been initialized]
How to show this data in the ListView in Flutter?
Here is My Complete Project Flutter:
The Url Parse:
http://jsonplaceholder.typicode.com/users
Main.dart
import 'package:flutter/material.dart';
import 'json_parse_demo.dart';
void main() {
runApp(const HomeApp());
}
class HomeApp extends StatelessWidget {
const HomeApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: JsonParseDemo(),
);
}
}
users.dart
// To parse this JSON data, do
//
// final users = usersFromJson(jsonString);
// ignore_for_file: file_names
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
User({
required this.user,
});
List<UserElement> user;
factory User.fromJson(Map<String, dynamic> json) => User(
user: List<UserElement>.from(
json["User"].map((x) => UserElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"User": List<dynamic>.from(user.map((x) => x.toJson())),
};
}
class UserElement {
UserElement({
required this.id,
required this.name,
required this.username,
required this.email,
required this.address,
required this.phone,
required this.website,
required this.company,
});
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
factory UserElement.fromJson(Map<String, dynamic> json) => UserElement(
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(),
};
}
class Address {
Address({
required this.street,
required this.suite,
required this.city,
required this.zipcode,
required this.geo,
});
String street;
String suite;
String city;
String zipcode;
Geo geo;
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
Geo({
required this.lat,
required this.lng,
});
String lat;
String lng;
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
Company({
required this.name,
required this.catchPhrase,
required this.bs,
});
String name;
String catchPhrase;
String bs;
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
servicios.dart
import 'package:http/http.dart' as http;
import 'users.dart';
class Services {
//
static Uri uri = Uri.parse('http://jsonplaceholder.typicode.com/users');
static Future<List<User>> getUsers() async {
try {
final response = await http.get(uri);
if (200 == response.statusCode) {
final List<User> users = userFromJson(response.body) as List<User>;
return users;
} else {
return <User>[];
}
} catch (e) {
return <User>[];
}
}
}
json_parse_demo.dart
// ignore_for_file: unnecessary_null_comparison
import 'package:flutter/material.dart';
import 'users.dart';
import 'servicios.dart';
class JsonParseDemo extends StatefulWidget {
//
const JsonParseDemo({Key? key}) : super(key: key);
#override
_JsonParseDemoState createState() => _JsonParseDemoState();
}
class _JsonParseDemoState extends State<JsonParseDemo> {
//
late List<User> _users;
// late bool _loading;
bool _loading = true;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: null == _users ? 0 : _users.length,
itemBuilder: (context, index) {
UserElement user = _users[index] as UserElement;
return ListTile(
title: Text(user.name),
subtitle: Text(user.email),
);
},
),
),
);
}
}
Make a function of future with async return then call it function in initstate (){}.
Because getUser api call is a asynchronous task.
Change your code like this.
#override
void initState() {
super.initState();
_loading = true;
getUserApiCall ();
}
Future getUserApiCall() async{
return await Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
If you facing any issues let me know

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' why this error coming

how to load value from api to fields when the api response json is complex ?
{
"agent":{
"agent_name": "Shamsudheen",
"agent_phone": "0581476710",
"email": "shamsu#gmail.com",
},
"tenants": [
{
"entity_id": "152",
"user_id": "37",
},
{
"entity_id": "153",
"user_id": "37",
},
{
"entity_id": "150",
"user_id": "37",
}
]
}
and this is my model class
class AgentDetailsInfo {
String name;
String email;
String mobile;
List<Tenantdetails> list;
AgentDetailsInfo(
{
this.name,
this.email,
this.mobile,
this.list
});
factory AgentDetailsInfo.fromJson(Map<String, dynamic> json) {
return new AgentDetailsInfo(
name: json['agent']['agent_name'],
email: json['agent']['email'],
mobile: json['agent']['agent_phone']
List:json[’tenants’]
);
}
}
class Tenantdetails {
String entity;
String userid;
Tenantdetails({
this.entity,
this.userid,
});
factory Tenantdetails.fromJson(Map<String, dynamic> json) {
return new Tenantdetails(
entity: json['tenants']['entity_id'],
userid: json['tenants']['user_id'],
);
}
}
and am calling api like this response coming perfectly but value is nitf
List<AgentDetailsInfo> _list;
Future getAgentDetails(String agentId) async {
String tokenKey = await SharedPrefUtils.readPrefStr("token");
String url =
Constants.BASEURL + Constants.KEYWORD_GET_AGENT_DETAILS + agentId;
final response = await http.get(
url,
headers: {"Accept": "application/json", "Authorization": tokenKey},
);
var response = jsonDecode(response.body);
_list = List();
for (Map agentinfo in response) {
_list.add(AgentDetailsInfo.fromJson(agentinfo));
}
}
but its not loading in my text view showing error
"_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable"
Text(_list[0].name,
))
You can copy paste run full code below
Step 1: Based on your JSON String, you need class Agent, see full code below
Step 2: You can parse with agentDetailsInfoFromJson(response.body);
code snippet
AgentDetailsInfo agentDetailsInfoFromJson(String str) =>
AgentDetailsInfo.fromJson(json.decode(str));
...
class AgentDetailsInfo {
AgentDetailsInfo({
this.agent,
this.tenants,
});
Agent agent;
List<Tenantdetails> tenants;
...
class Agent {
Agent({
this.agentName,
this.agentPhone,
this.email,
});
String agentName;
String agentPhone;
String email;
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
AgentDetailsInfo agentDetailsInfoFromJson(String str) =>
AgentDetailsInfo.fromJson(json.decode(str));
String agentDetailsInfoToJson(AgentDetailsInfo data) =>
json.encode(data.toJson());
class AgentDetailsInfo {
AgentDetailsInfo({
this.agent,
this.tenants,
});
Agent agent;
List<Tenantdetails> tenants;
factory AgentDetailsInfo.fromJson(Map<String, dynamic> json) =>
AgentDetailsInfo(
agent: Agent.fromJson(json["agent"]),
tenants: List<Tenantdetails>.from(
json["tenants"].map((x) => Tenantdetails.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"agent": agent.toJson(),
"tenants": List<dynamic>.from(tenants.map((x) => x.toJson())),
};
}
class Agent {
Agent({
this.agentName,
this.agentPhone,
this.email,
});
String agentName;
String agentPhone;
String email;
factory Agent.fromJson(Map<String, dynamic> json) => Agent(
agentName: json["agent_name"],
agentPhone: json["agent_phone"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"agent_name": agentName,
"agent_phone": agentPhone,
"email": email,
};
}
class Tenantdetails {
Tenantdetails({
this.entityId,
this.userId,
});
String entityId;
String userId;
factory Tenantdetails.fromJson(Map<String, dynamic> json) => Tenantdetails(
entityId: json["entity_id"],
userId: json["user_id"],
);
Map<String, dynamic> toJson() => {
"entity_id": entityId,
"user_id": userId,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Function _future;
Future<AgentDetailsInfo> getAgentDetails(String agentId) async {
print(agentId);
/*String tokenKey = await SharedPrefUtils.readPrefStr("token");
String url = Constants.BASEURL + Constants.KEYWORD_GET_AGENT_DETAILS + agentId;
final response = await http.get(
url,
headers: {"Accept": "application/json", "Authorization": tokenKey},
);*/
String jsonString = '''
{
"agent":{
"agent_name": "Shamsudheen",
"agent_phone": "0581476710",
"email": "shamsu#gmail.com"
},
"tenants": [
{
"entity_id": "152",
"user_id": "37"
},
{
"entity_id": "153",
"user_id": "37"
},
{
"entity_id": "150",
"user_id": "37"
}
]
}
''';
http.Response response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
return agentDetailsInfoFromJson(response.body);
}
}
#override
void initState() {
_future = getAgentDetails;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future("test"),
builder: (context, AsyncSnapshot<AgentDetailsInfo> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.tenants.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data.agent.agentName
.toString()),
Spacer(),
Text(snapshot.data.tenants[index].userId
.toString()),
Spacer(),
Text(snapshot.data.tenants[index].entityId),
],
),
));
});
}
}
}));
}
}

how to get data from api(Map type) for dropdown option

I have a problem when i want to get data from api and show them in dropdown option, I can print data when i run my code but in dropdown option i have below error :
type '(dynamic) => DropdownMenuItem' is not a subtype of type '(String, dynamic) => MapEntry' of 'transform'
import 'package:flutter/material.dart';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:http/http.dart' as http;
import 'dart:async';`enter code here`
import 'dart:convert';
class InBoundRate extends StatefulWidget {
#override
_InBoundRateState createState() => _InBoundRateState();
}
class _InBoundRateState extends State<InBoundRate> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: new Center(
child: new FutureBuilder(
future: GetInbound(),
builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
if (snapshot.hasData) {
Map content = snapshot.data ;
var sampleData = json.encode(content);
var json2 = JsonDecoder().convert(sampleData);
// print(json2['data']['countries']);
return DropdownButton(
items: json2.map(
(item) => DropdownMenuItem(
value: item['data']['countries'],
child: Text(item['data']['countries'])),
// onChanged: (Users value) {
// setState(() {
// _currentUser = value;
// });
// }
),
isExpanded: false,
//value: _currentUser,
hint: Text('Select User'),
);
} else {
return new Container();
}
}),
),
);
}
}
Future<Map> GetInbound() async {
String apiUrl = 'http://homaexpressco.ir/api/getRatesInformation2';
http.Response response = await http.get(apiUrl);
var res = json.decode(response.body);
return res;
}

Categories

Resources