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-preferencesvar.I've created this method in constants file to access from everywhere. It's your choice where you put it.
This is login method
Now you can access this myToken value from everywhere.
or directly