I am getting my response from the URL after login in but I can only print the data in my console but how to get the mail and name from the that response
I have tried with the future response but when I get a future response but its returning error
LoginPage.dart
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'globals.dart' as globals;
class LoginPage extends StatefulWidget {
static String tag = 'login-page';
#override
_LoginPageState createState() => new _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
LoginRequestData _loginData = LoginRequestData();
bool _validate = false;
bool _obscureText = true;
var username, password;
#override
Widget build(BuildContext context) {
return Scaffold(
// backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
color: Colors.lightGreen[500],
child: Column(
children: <Widget>[
Center(
child: Container(
width: MediaQuery
.of(context)
.size
.width,
height: MediaQuery
.of(context)
.size
.height / 2.5,
decoration: BoxDecoration(
gradient: LinearGradient(
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
colors: [
Color(0xFFFFFFFF),
Color(0xFFFFFFFF),
]
),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(90)
)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Align(
alignment: Alignment.center,
child: Image.asset('images/ic_launcher1.png'),
),
],
),
),
),
Center(
child: SingleChildScrollView(
child: new Form(
key: _formKey,
autovalidate: _validate,
child: _getFormUI(),
),
)
)
],
),
),
),
);
}
Widget _getFormUI() {
return new Column(
children: <Widget>[
SizedBox(height: 24.0),
Center(
child: Text('Login',
style: TextStyle(fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.white),),
),
new SizedBox(height: 25.0),
new TextFormField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: InputDecoration(
hintText: 'Username',
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
),
validator: _validateName,
onSaved: (value) {
_loginData.username = value;
},
),
new SizedBox(height: 8.0),
new TextFormField(
autofocus: false,
obscureText: _obscureText,
keyboardType: TextInputType.text,
decoration: InputDecoration(
hintText: 'Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(24.0)),
suffixIcon: GestureDetector(
child: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
semanticLabel:
_obscureText ? 'show password' : 'hide password',
),
),
),
validator: _validatePassword,
onSaved: (String value) {
_loginData.password = value;
}
),
new SizedBox(height: 15.0),
new Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
onPressed: () {
_submit();
// Navigator.of(context).pushReplacementNamed('/home');
},
padding: EdgeInsets.all(12),
color: Colors.black54,
child: Text('Log In', style: TextStyle(color: Colors.white)),
),
),
new FlatButton(
child: Text(
'Forgot password?',
style: TextStyle(color: Colors.black54),
),
onPressed: () {},
),
new FlatButton(
onPressed: _sendToRegisterPage,
child: Text('Not a member? Sign up now',
style: TextStyle(color: Colors.black54)),
),
Text(''),
Text(''),
Text(''),
],
);
}
_sendToRegisterPage() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
}
String _validateName(String value) {
if (value.isEmpty) {
return "Username is Required";
} else {
username = value.toString();
}
}
String _validatePassword(String value) {
if (value.isEmpty) {
return "Password is Required";
} else {
password = value.toString();
}
}
_submit() {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
print("Username ${_loginData.username}");
print("Password ${_loginData.password}");
return SessionId();
} else {
setState(() {
bool _validate = false;
});
}
}
final Dio _dio = Dio();
PersistCookieJar persistentCookies;
final String url = "https://www.xxxx.in/rest/user/login.json";
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print(directory.path);
return directory.path;
}
Future<Directory> get _localCoookieDirectory async {
final path = await _localPath;
final Directory dir = new Directory('$path/cookies');
await dir.create();
print(dir);
return dir;
}
Future<String> getCsrftoken() async{
try {
String csrfTokenValue;
final Directory dir = await _localCoookieDirectory;
final cookiePath = dir.path;
persistentCookies = new PersistCookieJar(dir: '$cookiePath');
persistentCookies.deleteAll(); //clearing any existing cookies for a fresh start
_dio.interceptors.add(
CookieManager(persistentCookies) //this sets up _dio to persist cookies throughout subsequent requests
);
_dio.options = new BaseOptions(
baseUrl: url,
contentType: ContentType.json,
responseType: ResponseType.plain,
// connectTimeout: 5000,
// receiveTimeout: 100000,
headers: {
HttpHeaders.userAgentHeader: "dio",
"Connection": "keep-alive",
},
); //BaseOptions will be persisted throughout subsequent requests made with _dio
_dio.interceptors.add(
InterceptorsWrapper(
onResponse:(Response response) {
List<Cookie> cookies = persistentCookies.loadForRequest(Uri.parse(url));
csrfTokenValue = cookies.firstWhere((c) => c.name == 'csrftoken', orElse: () => null)?.value;
if (csrfTokenValue != null) {
_dio.options.headers['X-CSRF-TOKEN'] = csrfTokenValue; //setting the csrftoken from the response in the headers
}
print(response);
return response;
}
)
);
await _dio.get("https://www.xxxx.in/rest/user/login.json");
print(csrfTokenValue);
return csrfTokenValue;
} catch (error, stacktrace) {
print(error);
// print("Exception occured: $error stackTrace: $stacktrace");
return null;
}
}
SessionId() async {
try {
final csrf = await getCsrftoken();
FormData formData = new FormData.from({
"username": "${_loginData.username}",
"password": "${_loginData.password}",
"csrfmiddlewaretoken" : '$csrf'
});
Options optionData = new Options(
contentType: ContentType.parse("application/json"),
);
Response response = await _dio.post("https://www.xxxx.in/rest/user/login.json", data: formData, options: optionData);
Payload payloadFromJson(String str) =>
Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
if (response.statusCode == 200){
return Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => HomeScreen(),
));
}
else{
throw Exception();
}
} on DioError catch(e) {
if(e.response != null) {
print( e.response.statusCode.toString() + " " + e.response.statusMessage);
print(e.response.data);
print(e.response.headers);
print(e.response.request);
} else{
print(e.request);
print(e.message);
}
}
catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return null;
}
}
}
Homepage.dart
import 'package:flutter/material.dart';
...
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => new _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xffF2F2F2),
appBar: AppBar(
title: Text('Home'),
automaticallyImplyLeading: true,
drawer: new Drawer(
child: Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("${globals.payload.user.name}"),
accountEmail: Text("${globals.payload.user.mail}"),
)
],
)
)
}
please anybody can help to display name and mail-in drawer
Here is my Json
{
"sessid": "iszSjigXjxCvchpSRrU3j5Xp83t_LCXoIbwzx-mM3ag",
"session_name": "SSESSb2a6bc76023596a5f4079539da5ffe57",
"token": "zQESYCrGbL-3NzN8Lm-1ll3AQ-iCFYjiqRvxSpesGBc",
"user": {
"uid": "991",
"name": "abc",
"mail": "abc#gmail.com",
"theme": "",
"signature": "",
"signature_format": "plain_text",
"created": "1560678471",
"access": "1565326417",
"login": 1565328198,
"status": "1",
"timezone": "Asia/Kolkata",
"language": "",
"picture": "0",
"data": {
"mimemail_textonly": 0
},
"uuid": "9e614051-1f21-470a-9194-c567fced36f7",
"roles": {
"2": "authenticated user",
"6": "Mock test user"
},
"rdf_mapping": {
"rdftype": [
"sioc:UserAccount"
],
"name": {
"predicates": [
"foaf:name"
]
},
"homepage": {
"predicates": [
"foaf:page"
],
"type": "rel"
}
}
}
}
Find Json file here
In comments, how to parse the JSON?
please paste your JSON string to https://app.quicktype.io/
It will provide correct format
code snippet to parse JSON.
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String sessid;
String sessionName;
String token;
User user;
Payload({
this.sessid,
this.sessionName,
this.token,
this.user,
});
factory Payload.fromJson(Map<String, dynamic> json) => new Payload(
sessid: json["sessid"],
sessionName: json["session_name"],
token: json["token"],
user: User.fromJson(json["user"]),
);
Map<String, dynamic> toJson() => {
"sessid": sessid,
"session_name": sessionName,
"token": token,
"user": user.toJson(),
};
}
class User {
String uid;
String name;
String mail;
String theme;
String signature;
String signatureFormat;
String created;
String access;
int login;
String status;
String timezone;
String language;
String picture;
Data data;
String uuid;
Map<String, String> roles;
RdfMapping rdfMapping;
User({
this.uid,
this.name,
this.mail,
this.theme,
this.signature,
this.signatureFormat,
this.created,
this.access,
this.login,
this.status,
this.timezone,
this.language,
this.picture,
this.data,
this.uuid,
this.roles,
this.rdfMapping,
});
factory User.fromJson(Map<String, dynamic> json) => new User(
uid: json["uid"],
name: json["name"],
mail: json["mail"],
theme: json["theme"],
signature: json["signature"],
signatureFormat: json["signature_format"],
created: json["created"],
access: json["access"],
login: json["login"],
status: json["status"],
timezone: json["timezone"],
language: json["language"],
picture: json["picture"],
data: Data.fromJson(json["data"]),
uuid: json["uuid"],
roles: new Map.from(json["roles"]).map((k, v) => new MapEntry<String, String>(k, v)),
rdfMapping: RdfMapping.fromJson(json["rdf_mapping"]),
);
Map<String, dynamic> toJson() => {
"uid": uid,
"name": name,
"mail": mail,
"theme": theme,
"signature": signature,
"signature_format": signatureFormat,
"created": created,
"access": access,
"login": login,
"status": status,
"timezone": timezone,
"language": language,
"picture": picture,
"data": data.toJson(),
"uuid": uuid,
"roles": new Map.from(roles).map((k, v) => new MapEntry<String, dynamic>(k, v)),
"rdf_mapping": rdfMapping.toJson(),
};
}
class Data {
int mimemailTextonly;
Data({
this.mimemailTextonly,
});
factory Data.fromJson(Map<String, dynamic> json) => new Data(
mimemailTextonly: json["mimemail_textonly"],
);
Map<String, dynamic> toJson() => {
"mimemail_textonly": mimemailTextonly,
};
}
class RdfMapping {
List<String> rdftype;
Name name;
Homepage homepage;
RdfMapping({
this.rdftype,
this.name,
this.homepage,
});
factory RdfMapping.fromJson(Map<String, dynamic> json) => new RdfMapping(
rdftype: new List<String>.from(json["rdftype"].map((x) => x)),
name: Name.fromJson(json["name"]),
homepage: Homepage.fromJson(json["homepage"]),
);
Map<String, dynamic> toJson() => {
"rdftype": new List<dynamic>.from(rdftype.map((x) => x)),
"name": name.toJson(),
"homepage": homepage.toJson(),
};
}
class Homepage {
List<String> predicates;
String type;
Homepage({
this.predicates,
this.type,
});
factory Homepage.fromJson(Map<String, dynamic> json) => new Homepage(
predicates: new List<String>.from(json["predicates"].map((x) => x)),
type: json["type"],
);
Map<String, dynamic> toJson() => {
"predicates": new List<dynamic>.from(predicates.map((x) => x)),
"type": type,
};
}
class Name {
List<String> predicates;
Name({
this.predicates,
});
factory Name.fromJson(Map<String, dynamic> json) => new Name(
predicates: new List<String>.from(json["predicates"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"predicates": new List<dynamic>.from(predicates.map((x) => x)),
};
}
In comments, the following code is for demo purpose only, not best practice, there are other options can do this, but hard to describe in short since it's a huge topic, so from Global Variables in Dart
1 add globals.dart file
library my_prj.globals;
//import Payload class file too
Payload payload;
2 Import this library everywhere you need access to these fields.
import 'globals.dart' as globals;
...
globals.payload = payloadFromJson(jsonString); //from your parse or http logical
3 In your drawer class
import 'globals.dart' as globals;
...
return Drawer(
child: Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("${globals.payload.user.name}"),
accountEmail: Text("${globals.payload.user.mail}"),
Edit
In Homepage.dart add the following, then you can access your global variables
import 'globals.dart' as globals;
and do the same in LoginPage.dart, then you can
globals.payload = payloadFromJson(jsonString);
In theory, you will need an object which has a similar structure. However, if the JSON is complex and you need one/two attributes, following can be the quick way.
_emailId = decodedBody["user"]["mail"]
Now, let's say you get JSON response in the login page and need to pass _emailId to HomePage. You can do this like below :
HomePage.dart
class HomePage extends StatelessWidget {
final String emailId;
const HomePage({
Key key,
#required this.emailId,
}) : super(key: key);
#override
Widget build(BuildContext context) {
print (this.emailid);
return .....
);
}
}
Update _sendToRegisterPage() as below :
_sendToRegisterPage() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen(emailId:_emailId)),
);
}
Related
i tried to decode my json and take the values to futurebuilder in flutter when decode my json appear formatexception:unexpectedcharacter,tried to storage in a String and in List, think my error think is how to toke data,how to storage my json decode,
Thanks
my code
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:oauth2_client/spotify_oauth2_client.dart';
import 'package:ui/Models/segundapantalla.dart';
import 'newmodel.dart';
class callttoappi {
Future getatatodapi() async {
String url =
'https://api.spotify.com/v1/playlists/37i9dQZF1DXcBWIGoYBM5M/tracks';
var client = SpotifyOAuth2Client(
redirectUri: 'com.example.ui://callback',
customUriScheme: 'com.example.ui');
var tknResp = await client.getTokenWithAuthCodeFlow(
clientId: 'client id',
scopes: [
'user-read-email',
'user-read-private',
]);
if (tknResp != null) {
var headers = {
'Authorization': 'Bearer ${tknResp.accessToken}',
};
var request = await http.Request(
'GET', Uri.parse('https://api.spotify.com/v1/browse/new-releases'));
request.headers.addAll(headers);
http.StreamedResponse response =
await request.send().timeout(const Duration(seconds: 20));
if (response.statusCode == 200) {
//String reponsedata = await response.stream.bytesToString();
//print(await response.stream.bytesToString());
Map<String, dynamic> userMap = jsonDecode(await response.stream.bytesToString());
var user = Item.fromJson(userMap);
print(userMap);
//Map<String,dynamic> json = jsonDecode(await response.stream.bytesToString());
//print(json);
return Item.fromJson(jsonDecode(json.toString()));
} else {
print(response.reasonPhrase);
}
}
}
}
my model class,quicktype website or another page this like github projects to obtain my json
class Newmodel {
Newmodel({
required this.albums,
});
final Albums? albums;
factory Newmodel.fromJson(Map<String, dynamic> json){
return Newmodel(
albums: json["albums"] == null ? null : Albums.fromJson(json["albums"]),
);
}
Map<String, dynamic> toJson() => {
"albums": albums?.toJson(),
};
#override
String toString(){
return '$albums';
}
}
class Albums {
Albums({
required this.href,
required this.items,
required this.limit,
required this.next,
required this.offset,
required this.previous,
required this.total,
});
final String? href;
final List<Item> items;
final int? limit;
final String? next;
final int? offset;
final dynamic previous;
final int? total;
factory Albums.fromJson(Map<String, dynamic> json){
return Albums(
href: json["href"],
items: json["items"] == null ? [] : List<Item>.from(json["items"]!.map((x) => Item.fromJson(x))),
limit: json["limit"],
next: json["next"],
offset: json["offset"],
previous: json["previous"],
total: json["total"],
);
}
Map<String, dynamic> toJson() => {
"href": href,
"items": List<Item>.from(items.map((x) => x.toJson())),
"limit": limit,
"next": next,
"offset": offset,
"previous": previous,
"total": total,
};
#override
String toString(){
return '$href, $items, $limit, $next, $offset, $previous, $total';
}
}
class Item {
Item({
required this.albumType,
required this.artists,
required this.availableMarkets,
required this.externalUrls,
required this.href,
required this.id,
required this.images,
required this.name,
required this.releaseDate,
required this.releaseDatePrecision,
required this.totalTracks,
required this.type,
required this.uri,
});
final String? albumType;
final List<Artist> artists;
final List<String> availableMarkets;
final ExternalUrls? externalUrls;
final String? href;
final String? id;
final List<Image> images;
final String? name;
final DateTime? releaseDate;
final String? releaseDatePrecision;
final int? totalTracks;
final String? type;
final String? uri;
factory Item.fromJson(Map<String, dynamic> json){
return Item(
albumType: json["album_type"],
artists: json["artists"] == null ? [] : List<Artist>.from(json["artists"]!.map((x) => Artist.fromJson(x))),
availableMarkets: json["available_markets"] == null ? [] : List<String>.from(json["available_markets"]!.map((x) => x)),
externalUrls: json["external_urls"] == null ? null : ExternalUrls.fromJson(json["external_urls"]),
href: json["href"],
id: json["id"],
images: json["images"] == null ? [] : List<Image>.from(json["images"]!.map((x) => Image.fromJson(x))),
name: json["name"],
releaseDate: json["release_date"] == null ? null : DateTime.parse(json["release_date"]),
releaseDatePrecision: json["release_date_precision"],
totalTracks: json["total_tracks"],
type: json["type"],
uri: json["uri"],
);
}
Map<String, dynamic> toJson() => {
"album_type": albumType,
"artists": List<Artist>.from(artists.map((x) => x.toJson())),
"available_markets": List<String>.from(availableMarkets.map((x) => x)),
"external_urls": externalUrls?.toJson(),
"href": href,
"id": id,
"images": List<Image>.from(images.map((x) => x.toJson())),
"name": name,
//"release_date": "${releaseDate.year.toString().padLeft(4'0')}-${releaseDate.month.toString().padLeft(2'0')}-${releaseDate.day.toString().padLeft(2'0')}",
"release_date_precision": releaseDatePrecision,
"total_tracks": totalTracks,
"type": type,
"uri": uri,
};
#override
String toString(){
return '$albumType, $artists, $availableMarkets, $externalUrls, $href, $id, $images, $name, $releaseDate, $releaseDatePrecision, $totalTracks, $type, $uri';
}
}
viewpage class
class lodeo extends StatefulWidget {
#override
State<lodeo> createState() => _WeatherPageState();
}
class _WeatherPageState extends State<lodeo> {
Future getData() async {
return await callttoappi().getatatodapi();
}
Future<dynamic>? _myData;
#override
void initState() {
setState(() {
_myData = getData();
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If error occured
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error.toString()} occurred',
style: TextStyle(fontSize: 18),
),
);
// if data has no errors
} else if (snapshot.hasData) {
// Extracting data from snapshot object
final data = snapshot.data as Item;
return Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment(0.8, 1),
colors: <Color>[
Color.fromARGB(255, 65, 89, 224),
Color.fromARGB(255, 83, 92, 215),
Color.fromARGB(255, 86, 88, 177),
Color(0xfff39060),
Color(0xffffb56b),
],
tileMode: TileMode.mirror,
),
),
width: double.infinity,
height: double.infinity,
child: SafeArea(
child: Column(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data.albumType.toString(),
style: TextStyle(
fontSize: 30,
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
data.id.toString(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
data.name.toString(),
style: TextStyle(
fontSize: 50,
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
),
),
],
),
),
);
}
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Center(
child: Text("${snapshot.connectionState} occured"),
);
}
return Center(
child: Text("Server timed out!"),
);
},
future: _myData!,
),
);
}
enter code here
Hi need help to show my API data into Text.
I already get the response but I don't know how to turn it into text which it will show at the screen.. now the data are shows at the terminal.
This is my codes:
class carList extends StatefulWidget {
const carList({Key? key}) : super(key: key);
#override
State<carList> createState() => _carListState();
}
class _carListState extends State<carList> {
var userController = TextEditingController();
var apiController = TextEditingController();
final pref = Pref();
#override
void initState() {
MySharedPreferences().getUserId().then((value) {
setState(() {
userController.text = value.toString();
});
});
MySharedPreferences().getUserToken().then((value) {
setState(() {
apiController.text = value.toString();
});
});
//TODO: IMPLEMENT INITSTATE
}
this is where I want to show my API data
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: userController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email),
labelText: 'User ID',
),
),
),
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: apiController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email),
labelText: 'Token',
),
),
),
Container(
margin: EdgeInsets.all(25),
child: TextButton(
child: Text('Show Car List',
style: TextStyle(fontSize: 20.0,
color: Colors.blueAccent,
backgroundColor: Colors.white),
),
onPressed: () {
list();
},
),
)
]
)
);
}
this is my API response
void list() async {
{
var response = await http.post(
Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
body: ({
'user_id': userController.text,
'token': apiController.text,
'device': "Android",
}));
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
print(apiController.text);
print(body.toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Successfully Login")));
}
}
}
}
This page that I want to show my data.
this is my log response
{
"Status": "OK",
"Message": "Senarai maklumat kereta.",
"Details": [
{
"car_id": 184,
"user_id": 141,
"manufacturer_id": 21,
"name": "Akma",
"registration_no": "ws 3345",
"model_name": "Bezza",
"production_year": 2022,
"notes": null,
"date_purchased": "2022-08-10",
"image":
" http://servisjer.me-tech.com.my/admin/storage/app/media/userplugin/7PyVIp8iwb.png"
}
]
}
Best way to use API response data is to create model from https://app.quicktype.io/ (copy your response and paste on this link and select language dart) and use as per your requirement.
I create model with name "GetUserCarModel" from your API response and use like this way.
Future<void> list() async {
{
var response = await http.post(
Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
body: ({
'user_id': userController.text,
'token': apiController.text,
'device': "Android",
})
);
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
GetUserCarModel getUserCarModel = GetUserCarModel.fromJson(body);
print("getUserCarModel ===> ${getUserCarModel.toString()}");
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Successfully Login")));
}
}
}
First of all you have to crate a model class of your response.
import 'dart:convert';
CarDetailResponse carDetailResponseFromJson(String str) => CarDetailResponse.fromJson(json.decode(str));
String carDetailResponseToJson(CarDetailResponse data) => json.encode(data.toJson());
class CarDetailResponse {
CarDetailResponse({
this.status,
this.message,
this.details,
});
String? status;
String? message;
List<Detail>? details;
factory CarDetailResponse.fromJson(Map<String, dynamic> json) => CarDetailResponse(
status: json["Status"],
message: json["Message"],
details: List<Detail>.from(json["Details"].map((x) => Detail.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Details": List<dynamic>.from(details!.map((x) => x.toJson())),
};
}
class Detail {
Detail({
this.carId,
this.userId,
this.manufacturerId,
this.name,
this.registrationNo,
this.modelName,
this.productionYear,
this.notes,
this.datePurchased,
this.image,
});
int? carId;
int? userId;
int? manufacturerId;
String? name;
String? registrationNo;
String? modelName;
int? productionYear;
dynamic notes;
DateTime? datePurchased;
String? image;
factory Detail.fromJson(Map<String, dynamic> json) => Detail(
carId: json["car_id"],
userId: json["user_id"],
manufacturerId: json["manufacturer_id"],
name: json["name"],
registrationNo: json["registration_no"],
modelName: json["model_name"],
productionYear: json["production_year"],
notes: json["notes"],
datePurchased: DateTime.parse(json["date_purchased"]),
image: json["image"],
);
Map<String, dynamic> toJson() => {
"car_id": carId,
"user_id": userId,
"manufacturer_id": manufacturerId,
"name": name,
"registration_no": registrationNo,
"model_name": modelName,
"production_year": productionYear,
"notes": notes,
"date_purchased": "${datePurchased!.year.toString().padLeft(4, '0')}-${datePurchased!.month.toString().padLeft(2, '0')}-${datePurchased!.day.toString().padLeft(2, '0')}",
"image": image,
};
}
you can make this model class with the help of app.quicktype.io
then after getting response, assign the response.body to this model class object
void list() async {
{
var response = await http.post(
Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
body: ({
'user_id': userController.text,
'token': apiController.text,
'device': "Android",
}));
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
setState(() {
carDetailResponse =
carDetailResponseFromJson(body);
});
print(apiController.text);
print(body.toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Successfully Login")));
}
}
}
}
then at UI use this model class to show data. Like -
class CarDetailScreen extends StatefulWidget {
const CarDetailScreen({Key? key}) : super(key: key);
#override
State<CarDetailScreen> createState() => _CarDetailScreenState();
}
class _CarDetailScreenState extends State<CarDetailScreen> {
CarDetailResponse? carDetailResponse;
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(children: <Widget>[
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: userController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email),
labelText: 'User ID',
),
),
),
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: apiController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email),
labelText: 'Token',
),
),
),
Container(
margin: EdgeInsets.all(25),
child: TextButton(
child: Text(
'Show Car List',
style: TextStyle(fontSize: 20.0, color: Colors.blueAccent, backgroundColor: Colors.white),
),
onPressed: () {
list();
},
),
),
carDetailResponse != null
? Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
itemCount: carDetailResponse!.details!.length,
itemBuilder: (context, index) {
var car = carDetailResponse!.details![index];
return Text(car.name ?? '');
},
),
)
: const SizedBox()
]));
}
}
assuming this is valid response :
{
"Status":"OK",
"Message":"Sena.",
"Details":[
{
"car_id":184,
"user_id":141,
"manufacturer_id":21,
"name":"Akma",
"registration_no":"ws 3345",
"model_name":"Bezza",
"production_year":2022,
"notes":null,
"date_purchased":"2022-08-10",
"image":"http://servisjer.me-tech.com.my/admin/storage/app/media/userplugin/7PyVIp8iwb.png"
}
]
}
then to get save the details is a list so you have to loop through the list i.e
if(body["Status"]=="OK")
{
List<Detail> allRecord;
final parsed = json.decode(body).cast<Map<String, dynamic>>();
allRecord = parsed .map<Detail>((json) => Detail.fromJson(json)).toList();
}
here is your model :
// To parse this JSON data, do
//
// final responseModel = responseModelFromJson(jsonString);
import 'dart:convert';
ResponseModel responseModelFromJson(String str) => ResponseModel.fromJson(json.decode(str));
String responseModelToJson(ResponseModel data) => json.encode(data.toJson());
class ResponseModel {
ResponseModel({
this.status,
this.message,
this.details,
});
String status;
String message;
List<Detail> details;
factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(
status: json["Status"],
message: json["Message"],
details: List<Detail>.from(json["Details"].map((x) => Detail.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Details": List<dynamic>.from(details.map((x) => x.toJson())),
};
}
class Detail {
Detail({
this.carId,
this.userId,
this.manufacturerId,
this.name,
this.registrationNo,
this.modelName,
this.productionYear,
this.notes,
this.datePurchased,
this.image,
});
int carId;
int userId;
int manufacturerId;
String name;
String registrationNo;
String modelName;
int productionYear;
dynamic notes;
DateTime datePurchased;
String image;
factory Detail.fromJson(Map<String, dynamic> json) => Detail(
carId: json["car_id"],
userId: json["user_id"],
manufacturerId: json["manufacturer_id"],
name: json["name"],
registrationNo: json["registration_no"],
modelName: json["model_name"],
productionYear: json["production_year"],
notes: json["notes"],
datePurchased: DateTime.parse(json["date_purchased"]),
image: json["image"],
);
Map<String, dynamic> toJson() => {
"car_id": carId,
"user_id": userId,
"manufacturer_id": manufacturerId,
"name": name,
"registration_no": registrationNo,
"model_name": modelName,
"production_year": productionYear,
"notes": notes,
"date_purchased": "${datePurchased.year.toString().padLeft(4, '0')}-${datePurchased.month.toString().padLeft(2, '0')}-${datePurchased.day.toString().padLeft(2, '0')}",
"image": image,
};
}
Worst Approach : use a for each to loop through if you are sure the Details array has only one object i.e
for (var data in details)
{
debugPrint(data.model_name);
debugPrint(data.registration_no);
//and many more
}
here is the error message from the console
user.dart
import 'package:cloud_firestore/cloud_firestore.dart';
class User {
final String email;
final String uid;
final String photoUrl;
final String username;
final String bio;
final List<String> followers;
final List<String> following;
const User({
required this.email,
required this.uid,
required this.photoUrl,
required this.username,
required this.bio,
required this.followers,
required this.following,
});
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
username: snapshot["username"],
uid: snapshot["uid"],
email: snapshot["email"],
photoUrl: snapshot["photoUrl"],
bio: snapshot["bio"],
followers: snapshot["followers"],
following: snapshot["following"],
);
}
Map<String, dynamic> toJson() => {
"username": username,
"uid": uid,
"email": email,
"photoUrl": photoUrl,
"bio": bio,
"followers": followers,
"following": following,
};
}
user_provider
import 'package:flutter/material.dart';
import 'package:social_network/models/user.dart';
import 'package:social_network/resources/auth_method.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
Future<void> refreshUser() async {
User? user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
add_post_screen
import 'dart:typed_data';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:social_network/providers/user_provider.dart';
import 'package:social_network/resources/firestore_methods.dart';
import 'package:social_network/utils/colors.dart';
import 'package:social_network/utils/utils.dart';
class AddPostScreen extends StatefulWidget {
const AddPostScreen({Key? key}) : super(key: key);
#override
_AddPostScreenState createState() => _AddPostScreenState();
}
class _AddPostScreenState extends State<AddPostScreen> {
Uint8List? _file;
bool _isLoading = false;
final TextEditingController _descriptionController = TextEditingController();
_selectImage(BuildContext parentContext) async {
return showDialog(
context: parentContext,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Create a post'),
children: <Widget>[
SimpleDialogOption(
padding: const EdgeInsets.all(20),
child: const Text('Take a photo'),
onPressed: () async {
Navigator.of(context).pop();
Uint8List file = await pickImage(ImageSource.camera);
setState(() {
_file = file;
});
},
),
SimpleDialogOption(
padding: const EdgeInsets.all(20),
child: const Text('Choose from gallery'),
onPressed: () async {
Navigator.of(context).pop();
Uint8List file = await pickImage(ImageSource.gallery);
setState(() {
_file = file;
});
},
),
SimpleDialogOption(
padding: const EdgeInsets.all(20),
child: const Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}
void postImage(
String uid,
String username,
String profileImage,
) async {
setState(() {
_isLoading = true;
});
try {
String res = await FirestoreMethods().uploadPost(
_descriptionController.text, _file!, uid, username, profileImage);
if (res == "Succes") {
setState(() {
_isLoading = false;
});
showSnackBar('Posted!', context);
clearImage();
} else {
showSnackBar(res, context);
}
} catch (e) {
setState(() {
_isLoading = false;
});
showSnackBar(e.toString(), context);
}
}
void clearImage() {
setState(() {
_file = null;
});
}
#override
void dispose() {
super.dispose();
_descriptionController.dispose();
}
#override
Widget build(BuildContext context) {
final UserProvider userProvider = Provider.of<UserProvider>(context);
return _file == null
? Center(
child: IconButton(
icon: const Icon(Icons.upload),
onPressed: () => _selectImage(context),
),
)
: Scaffold(
appBar: AppBar(
backgroundColor: mobileBackgroundColor,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: clearImage,
),
title: const Text('Post to'),
centerTitle: false,
actions: <Widget>[
TextButton(
onPressed: () => postImage(
userProvider.getUser.uid,
userProvider.getUser.username,
userProvider.getUser.photoUrl,
),
child: const Text(
'Post',
style: TextStyle(
color: Colors.redAccent,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
],
),
body: Column(
children: [
_isLoading
? const LinearProgressIndicator()
: const Padding(
padding: EdgeInsets.only(top: 0),
),
const Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(
backgroundImage: NetworkImage(
'https://images.unsplash.com/photo-1522441815192-d9f04eb0615c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=654&q=80',
// userProvider.getUser.photoUrl,
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.4,
child: TextField(
controller: _descriptionController,
decoration: const InputDecoration(
hintText: 'Write a caption...',
border: InputBorder.none,
),
maxLines: 8,
),
),
SizedBox(
height: 45,
width: 45,
child: AspectRatio(
aspectRatio: 487 / 451,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: MemoryImage(_file!),
fit: BoxFit.fill,
alignment: FractionalOffset.topCenter,
),
),
),
),
),
const Divider(),
],
)
],
));
}
}
auth_methods.dart
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:social_network/models/user.dart' as model;
import 'package:social_network/resources/storage_methods.dart';
class AuthMethods {
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<model.User?> getUserDetails() async {
User currentUser = _auth.currentUser!;
DocumentSnapshot documentSnapshot =
await _firestore.collection('user').doc(currentUser.uid).get();
return model.User.fromSnap(documentSnapshot);
}
//sign up the user
Future<String> signUpUser({
required String email,
required String password,
required String username,
required String bio,
required Uint8List? file,
}) async {
String res = "Some error occurred";
try {
if (email.isNotEmpty ||
password.isNotEmpty ||
username.isNotEmpty ||
bio.isNotEmpty ||
file != null) {
//register the user
UserCredential cred = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
String photoUrl = await StorageMethods()
.uploadImageToStorage('profilePictures', file!, false);
//adding user to our database
model.User _user = model.User(
bio: bio,
username: username,
uid: cred.user!.uid,
email: email,
photoUrl: photoUrl,
following: [],
followers: [],
);
await _firestore.collection("users").doc(cred.user!.uid).set(
_user.toJson(),
);
res = "Succes";
} else {
res = "Please enter all the fields";
}
} catch (err) {
res = err.toString();
}
return res;
}
// logging the user
Future<String> loginUser(
{required String email, required String password}) async {
String res = "Some error occured";
try {
if (email.isNotEmpty || password.isNotEmpty) {
await _auth.signInWithEmailAndPassword(
email: email, password: password);
res = "Succes";
} else {
res = "Please enter all the fields required";
}
} catch (err) {
res = err.toString();
}
return res;
}
}
Hello. I'll try to make a post button and when I try to upload a photo and press the post button I receive this error.
Do you have any solution for this error? Thanks a lot!
Error message:
Restarted application in 474ms.
[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
════════ Exception caught by gesture ═══════════════════════════════════════════
Null check operator used on a null value
════════════════════════════════════════════════════════════════════════════════
[VERBOSE-2:profiler_metrics_ios.mm(203)] Error retrieving thread information: (os/kern) object terminated
I believe that your issue in
onPressed: () => postImage(
userProvider.getUser.uid,
userProvider.getUser.username,
userProvider.getUser.photoUrl,
),
Make sure that the user is not null before calling the method,
It would be more helpful to post more code _authMethods.getUserDetails(); what’s inside this method?
UPDATE:
Future<model.User?> getUserDetails() async {
User currentUser = _auth.currentUser!;
DocumentSnapshot documentSnapshot =
await _firestore.collection('user').doc(currentUser.uid).get();
//add the following lines
print('documentSnapshot: $documentSnapshot');
if(documentSnapshot == null) return null;
return model.User.fromSnap(documentSnapshot);
}
eg: details about the questions .......................................................................... When I want to fetch multiple objects from an array showing status code 403(Failed to load post).and API having a header key I have implemented it also. but showing failed to load post status code 403.
{
"status": 1,
"msg": "7 banners found",
"data": [
{
"id": "14",
"image": "https://www.sofikart.com/admin/upload/app_banner/1635945056.jpeg",
"cat_id": "4",
"product_id": "81",
"url": null,
"status": "Active",
"ordering": "0",
"updated": "2021-11-03 06:10:56"
},
{
"id": "7",
"image": "https://www.sofikart.com/admin/upload/app_banner/1642082634.jpeg",
"cat_id": "4",
"product_id": "111",
"url": null,
"status": "Active",
"ordering": "1",
"updated": "2021-10-28 04:53:26"
}
]
}
controller
-----------
import 'dart:io';
import 'package:fm_sidharth/model/post.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
final String url = 'https://www.sofikart.com/MobileApi/banners';
Future<List<Post>> fetchPost() async {
final response = await http.get(
url, headers: {HttpHeaders.authorizationHeader: 'SOFIKART-*2021#',},);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final result = json.decode(response.body);
List<Post> posts =
result.map<Post>((model) => new Post.fromJson(model)).toList();
return posts;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Future<String> saveNetworkImageToPhoto(String url, String title,
{bool useCache: true}) async {
var data = await getNetworkImageData(url, useCache: useCache);
var filePath = await ImagePickerSaver.saveFile(fileData: data, title: title);
return filePath;
}
class ImagePickerSaver {
static saveFile({fileData, String title}) {}
}
getNetworkImageData(String url, {booluseCache, bool
useCache}) {
}
model
-------------
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
Post welcomeFromJson(String str) => Post.fromJson(json.decode(str));
String welcomeToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
this.status,
this.msg,
this.data,
});
int status;
String msg;
List<Datum> data;
factory Post.fromJson(Map<String, dynamic> json) => Post(
status: json["status"],
msg: json["msg"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
String get catId => null;
get image => null;
Map<String, dynamic> toJson() => {
"status": status,
"msg": msg,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.id,
this.image,
this.catId,
this.productId,
this.url,
this.status,
this.ordering,
this.updated,
});
String id;
String image;
String catId;
String productId;
dynamic url;
String status;
String ordering;
DateTime updated;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
image: json["image"],
catId: json["cat_id"],
productId: json["product_id"],
url: json["url"],
status: json["status"],
ordering: json["ordering"],
updated: DateTime.parse(json["updated"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"image": image,
"cat_id": catId,
"product_id": productId,
"url": url,
"status": status,
"ordering": ordering,
"updated": updated.toIso8601String(),
};
}
home
-----------
import 'package:flutter/material.dart';
import 'package:fm_sidharth/Controller/postController.dart';
import 'package:fm_sidharth/model/post.dart';
import 'package:fm_sidharth/page/postdetails.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<List<Post>> posts;
_HomePageState() {
posts = fetchPost();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: FutureBuilder<List<Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PostDetails(snapshot.data[index])),
);
},
child: Card(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data[index].catId,
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(
height: 10,
),
FadeInImage.assetNetwork(
image: snapshot.data[index].image,
placeholder: 'assets/images/noimage.png',
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
},
),
IconButton(
icon: Icon(Icons.save),
onPressed: () {
saveNetworkImageToPhoto(
snapshot.data[index].image,snapshot.data[index].catId).then((value){
});
},
),
],
)
],
),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(child: CircularProgressIndicator());
},
),
);
}
}
The HTTP 403 means that the access to the requested resource is forbidden. The server understood the request, but it is unable to fulfill it. Are you sure you sent the required(and correct) credentials to the server?
eg: details about the questions ..........................................................................
When I want to fetch multiple objects from an array showing status code 403(Failed to load post).and API having a header key I have implemented it also. but showing failed to load post status code 403.
{
"status": 1,
"msg": "7 banners found",
"data": [
{
"id": "14",
"image": "https://www.sofikart.com/admin/upload/app_banner/1635945056.jpeg",
"cat_id": "4",
"product_id": "81",
"url": null,
"status": "Active",
"ordering": "0",
"updated": "2021-11-03 06:10:56"
},
{
"id": "7",
"image": "https://www.sofikart.com/admin/upload/app_banner/1642082634.jpeg",
"cat_id": "4",
"product_id": "111",
"url": null,
"status": "Active",
"ordering": "1",
"updated": "2021-10-28 04:53:26"
}
]
}
controller
-----------
import 'dart:io';
import 'package:fm_sidharth/model/post.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
final String url = 'https://www.sofikart.com/MobileApi/banners';
Future<List<Post>> fetchPost() async {
final response = await http.get(
url, headers: {HttpHeaders.authorizationHeader: 'SOFIKART-*2021#',},);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final result = json.decode(response.body);
List<Post> posts =
result.map<Post>((model) => new Post.fromJson(model)).toList();
return posts;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Future<String> saveNetworkImageToPhoto(String url, String title,
{bool useCache: true}) async {
var data = await getNetworkImageData(url, useCache: useCache);
var filePath = await ImagePickerSaver.saveFile(fileData: data, title: title);
return filePath;
}
class ImagePickerSaver {
static saveFile({fileData, String title}) {}
}
getNetworkImageData(String url, {booluseCache, bool
useCache}) {
}
model
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
Post welcomeFromJson(String str) => Post.fromJson(json.decode(str));
String welcomeToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
this.status,
this.msg,
this.data,
});
int status;
String msg;
List<Datum> data;
factory Post.fromJson(Map<String, dynamic> json) => Post(
status: json["status"],
msg: json["msg"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
String get catId => null;
get image => null;
Map<String, dynamic> toJson() => {
"status": status,
"msg": msg,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.id,
this.image,
this.catId,
this.productId,
this.url,
this.status,
this.ordering,
this.updated,
});
String id;
String image;
String catId;
String productId;
dynamic url;
String status;
String ordering;
DateTime updated;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
image: json["image"],
catId: json["cat_id"],
productId: json["product_id"],
url: json["url"],
status: json["status"],
ordering: json["ordering"],
updated: DateTime.parse(json["updated"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"image": image,
"cat_id": catId,
"product_id": productId,
"url": url,
"status": status,
"ordering": ordering,
"updated": updated.toIso8601String(),
};
}
home
import 'package:flutter/material.dart';
import 'package:fm_sidharth/Controller/postController.dart';
import 'package:fm_sidharth/model/post.dart';
import 'package:fm_sidharth/page/postdetails.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<List<Post>> posts;
_HomePageState() {
posts = fetchPost();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: FutureBuilder<List<Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PostDetails(snapshot.data[index])),
);
},
child: Card(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data[index].catId,
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(
height: 10,
),
FadeInImage.assetNetwork(
image: snapshot.data[index].image,
placeholder: 'assets/images/noimage.png',
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
},
),
IconButton(
icon: Icon(Icons.save),
onPressed: () {
saveNetworkImageToPhoto(
snapshot.data[index].image,snapshot.data[index].catId).then((value){
});
},
),
],
)
],
),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(child: CircularProgressIndicator());
},
),
);
}
}
I have this error too some times, I think this about restrict that google set on you country. please use a proxy. I hope my answer helping to you :)