I have succeed to show my token when I have logged in, this token is to access the product page after login. The problem is my product page can only show data with token that I have but I don't know how to save my token and use it to show my the product data. I use Postman for my API and laravel.
My product code is only like this:
product.dart
class pageSuccess extends StatefulWidget {
@override
State<pageSuccess> createState() => _pageSuccessState();
}
class _pageSuccessState extends State<pageSuccess> {
var data;
//SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
//String token = sharedPreferences.getString(Constants.TOKEN)!;
Future<void> getUserApi() async {
final response =
await http.get(Uri.parse('http://10.0.2.2:8000/api/produk'),
headers:{
'Content-Type': 'text/html; charset=UTF-8',
//'Authorization' : 'Bearer $token',
},
);
var encodeFirst = json.encode(response.body.toString());
data = jsonDecode(encodeFirst.toString());
if (response.statusCode == 200) {
print(data);
print('product success');
} else {
print('product failed');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Api Course'),
),
body: Column(
children: [
Expanded(
child: FutureBuilder(
future: getUserApi(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('Loading');
} else {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: [
ReusbaleRow(
title: 'kode',
value: data[index]['kode'].toString(),
),
ReusbaleRow(
title: 'nama',
value: data[index]['nama'].toString(),
),
ReusbaleRow(
title: 'keterangan',
value: data[index]['keterangan'].toString(),
),
ReusbaleRow(
title: 'harga',
value: data[index]['harga'].toString(),
),
],
),
);
});
}
},
),
)
],
),
);
}
}
How do I usually do it (many people do it in many way)?
I'm getting the token when user login. So, I'm storing the token in a shared-preferences
var.
I've created this method in constants file to access from everywhere. It's your choice where you put it.
Map<String, String> headersWithToken = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $myToken'
};
String? myToken; // I'm changing this value when user success to login
class CurrentUserData {
saveUserData(String userToken) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setString('currentUserToken', userToken);
}
}
This is login method
if (response.statusCode == 201) { //login success status code 201
//print(data['success']);
var returnMsg = data['message'];
var userToken = data['token'],
setState(() {
myToken = userToken; //I've var
});
toastMsg(returnMsg);
CurrentUserData().saveUserData(userToken); //this method i'm accessing from constant file
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => const DashboardPage()), (route) => false);
}
Now you can access this myToken value from everywhere.
http.get(Url.perse(url), headers: headersWithToken)
or directly
var res = await http.get(
Uri.parse(userDashboardUrl),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $myToken'
},
);