Saving my Token generated from RestAPI to sharedpreferences in flutter code example
Example 1: Flutter not getting all data from api
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clickmeetplay/iam/user/postbean.dart';
import 'package:http/http.dart' as http;
class PostHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: PostScreen(),),);
}
}
class PostScreen extends StatefulWidget {
@override
_PostScreenState createState() => _PostScreenState();
}
class _PostScreenState extends State<PostScreen> {
List<Post> _postList =new List<Post>();
Future<List<Post> > fetchPost() async {
final response =
await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
List<dynamic> values=new List<dynamic>();
values = json.decode(response.body);
if(values.length>0){
for(int i=0;i<values.length;i++){
if(values[i]!=null){
Map<String,dynamic> map=values[i];
_postList .add(Post.fromJson(map));
debugPrint('Id-------${map['id']}');
}
}
}
return _postList;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
@override
Widget build(BuildContext context) {
return Container();
}
@override
void initState() {
fetchPost();
}
}
Example 2: How to send JSON Web Token (JWT Token) as header with Postman and golang
func ProtectedEndpoint(w http.ResponseWriter, req *http.Request) {
params := req.URL.Query()
token, _ := jwt.Parse(params["token"][0], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return []byte("secret"), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
var user User
mapstructure.Decode(claims, &user)
json.NewEncoder(w).Encode(user)
} else {
json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
}
}
Example 3: How to send JSON Web Token (JWT Token) as header with Postman and golang
func CreateTokenEndpoint(w http.ResponseWriter, req *http.Request) {
var user User
_ = json.NewDecoder(req.Body).Decode(&user)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
})
tokenString, error := token.SignedString([]byte("secret"))
if error != nil {
fmt.Println(error)
}
json.NewEncoder(w).Encode(JwtToken{Token: tokenString})
}