这可能是我第一次在Flutter中使用登录和注册。尽管这很有效,但我很难理解为什么当我尝试使用SharedPreferences
时,authentication_token
不会存储到本地存储中。每次我尝试访问令牌时,我都会收到以下错误:
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (16224): #0 Network.getToken
package:eatiano_app/…/network_utils/authentication.dart:18
E/flutter (16224): <asynchronous suspension>
E/flutter (16224):
D/EGL_emulation(16224): app_time_stats: avg=1023.77ms min=1.03ms max=13256.89ms count=18
D/EGL_emulation(16224): app_time_stats: avg=255.85ms min=34.01ms max=518.67ms count=4
我想弄清楚我做错了什么。这是我的代码:
网络类别:
class Network with ChangeNotifier {
String url = 'https://achievexsolutions.in/current_work/eatiano/';
var token;
bool _isAuth = false;
bool get auth {
return _isAuth;
}
getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
// token = jsonDecode(localStorage.getString('token') ?? '')['access_token'];
token = jsonDecode(localStorage.getString('token') ?? '')['token']; //line 18
print('Token $token');
}
authData(data, apiUrl) async {
var fullUrl = url + apiUrl;
return await http.post(Uri.parse(fullUrl),
body: jsonEncode(data), headers: _setHeaders());
}
getData(apiUrl) async {
var fullUrl = url + apiUrl;
await getToken(); //line 30
return await http.get(Uri.parse(fullUrl), headers: _setHeaders());
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
checkIfLoggedIn() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
token = localStorage.getString('token');
if (token != null) {
_isAuth = true;
notifyListeners();
}
}
}
这是我触发getToken()
方法的函数。(这是登录小部件中的登录功能(
void _login() async {
final data = {'email': inputEmail, 'password': inputPassword};
var res = await Provider.of<Network>(context, listen: false)
.authData(data, 'api/auth/login');
final provider =
Provider.of<LocationProvider>(context, listen: false).loading;
print(json.decode(res.body));
var body = json.decode(res.body);
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('token', json.encode(body['access_token']));
Navigator.of(context).pushReplacementNamed('/bottom-bar');
Provider.of<Network>(context, listen: false).getToken();
}
以下是我尝试注销时的错误:
E/flutter (16224): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (16224): #0 Network.getToken
package:eatiano_app/…/network_utils/authentication.dart:18
E/flutter (16224): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (16224): #0 Network.getToken
package:eatiano_app/…/network_utils/authentication.dart:18
E/flutter (16224): <asynchronous suspension>
E/flutter (16224): #1 Network.getData
package:eatiano_app/…/network_utils/authentication.dart:30
CCD_ 4和CCD_。
登录功能:
child: InkWell(
onTap: () async {
var res = await Provider.of<Network>(context, listen: false)
.getData('api/auth/logout');
var body = json.decode(res.body);
SharedPreferences localStorage =
await SharedPreferences.getInstance();
localStorage.remove('token');
Navigator.push(context,
MaterialPageRoute(builder: (context) => SignIn()));
},
登录或注册期间来自Laravel后端的响应:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYWNoaWV2ZXhzb2x1dGlvbnMuaW5cL2N1cnJlbnRfd29ya1wvZWF0aWFub1wvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTY0NjcyNDY2MCwiZXhwIjoxNjQ3OTM0MjYwLCJuYmYiOjE2NDY3MjQ2NjAsImp0aSI6IkJaY2FjbmJZV1A1OTd0a0siLCJzdWIiOjEwLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.n0M5ehm3BgP1Ctcvl_6Tt3rtYMeP1W6xgbN86LX1SLA",
"token_type": "bearer",
"role": "user",
"expires_in": 10596096000
}
解决方案
var decode = jsonDecode('{"access_tocken":"${localStorage.getString('tocken') ?? ''}"}')['access_tocken'];
print(decode);
修改你的gettocken方法
getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
// token = jsonDecode('{"access_tocken":"${localStorage.getString('tocken') ?? ''}"}')['access_tocken'];
token = jsonDecode(localStorage.getString('token') ?? '')['token']; //line 18
print('Token $token');
}
问题:
但你这样努力。jsonDecode(localStorage.getString('tocken') ??'')
解码localStorage.getString('tocken')
返回字符串不是json字符串,所以不能访问。jsonDecode(localStorage.getString('tocken') ??'')['access_tocken']
var decode = jsonDecode(localStorage.getString('tocken') ??'')['access_tocken'];
print(decode);
//output
type 'String' is not a subtype of type 'int' of 'index'