postman 如何使用带有承载令牌的get方法在flutter中显示来自API的数据

avkwfej4  于 2023-10-18  发布在  Postman
关注(0)|答案(1)|浏览(150)

我已经成功地显示我的令牌时,我已经登录,这个令牌是登录后访问产品页面。问题是我的产品页面只能显示我拥有的令牌数据,但我不知道如何保存我的令牌并使用它来显示我的产品数据。我使用Postman作为我的API和Laravel。
我的产品代码是这样的:
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(),
                              ),
                            ],
                          ),
                        );
                      });
                }
              },
            ),
          )
        ],
      ),
    );
  }
}
vc9ivgsu

vc9ivgsu1#

**我通常是怎么做的(很多人都是这么做的)?**我在用户登录时获取令牌。因此,我将令牌存储在shared-preferences var中。

我在常量文件中创建了这个方法,可以从任何地方访问。把它放在哪里是你的选择。

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);
  }
}

这是登录方式

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);
}

现在您可以从任何地方访问此myToken值。

http.get(Url.perse(url), headers: headersWithToken)

或直接

var res = await http.get(
    Uri.parse(userDashboardUrl),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $myToken'
    },
  );

相关问题