Flutter登录后以认证密钥为Header调用GET API失败,无法加载列表求助
Hey there, let's break down what's causing your problem and fix it step by step:
The Core Problem
Right now, you're using a hardcoded value ('xxxxxxxx') for your auth header, and it looks like either that value is invalid, or you're not using the correct header key your backend expects. Also, note that the auth key should come from your login API response (not the list API response)—you need to capture that key after login and pass it to your SecondScreen properly, instead of trying to pull it from the list request's response.
Step 1: Capture the Auth Key After Login
When your login request succeeds, extract the auth_key from the login response and either pass it directly to SecondScreen via the route, or store it locally (like using SharedPreferences for persistence across app sessions).
Option A: Pass Auth Key Directly via Route
In your login button's onPressed handler:
// After successful login, parse the login response to get the auth key final loginResponseJson = json.decode(loginApiResponse.body); final authKey = loginResponseJson['auth_key']; // Navigate to SecondScreen and pass the authKey as a parameter Navigator.push( context, MaterialPageRoute( builder: (context) => SecondScreen(authKey: authKey), ), );
Option B: Store Auth Key Locally with SharedPreferences
// After successful login final loginResponseJson = json.decode(loginApiResponse.body); final authKey = loginResponseJson['auth_key']; // Save the key to SharedPreferences for later use final prefs = await SharedPreferences.getInstance(); await prefs.setString('auth_key', authKey); // Navigate to SecondScreen Navigator.push(context, MaterialPageRoute(builder: (context) => SecondScreen()));
Step 2: Update SecondScreen to Use the Valid Auth Key
First, adjust your SecondScreen to receive the auth key (if using Option A):
class SecondScreen extends StatefulWidget { final String authKey; const SecondScreen({super.key, required this.authKey}); @override _SecondScreenState createState() => _SecondScreenState(); }
Then revise your getJsonData method to use the real auth key, and fix common pitfalls:
@override void initState() { super.initState(); getJsonData(); } // Update return type to Future<void> since we're not returning a request object Future<void> getJsonData() async { // If using Option B (SharedPreferences), fetch the key here: // final prefs = await SharedPreferences.getInstance(); // final authKey = prefs.getString('auth_key') ?? ''; final response = await http.get( // Use Uri.parse instead of the deprecated Uri.encodeFull for better URL handling Uri.parse("http://xxxxxx/xxxx/xxxx"), headers: { // Critical: Replace 'Header' with the actual header key your backend requires! // Common valid options include 'Authorization', 'X-Auth-Key', or 'Auth-Key' 'Auth-Key': widget.authKey, // Or authKey from SharedPreferences "Accept": "application/json", }, ); print(response.body); setState(() { final convertDatatoJson = json.decode(response.body); // Handle error case first to avoid null reference crashes if (!convertDatatoJson['error']) { data = convertDatatoJson['course_list']; } else { print('Failed to load data: ${convertDatatoJson['message']}'); } }); }
Key Things to Double-Check
- Header Key Name: Your backend's error message ("Auth key is not defined") almost always means you're using the wrong key in your headers. Confirm with your backend team or API docs what the correct header name is (e.g.,
Authorization: Bearer <token>orX-Auth-Token: <key>). - Valid Auth Key: Ensure the auth key you're passing is exactly the one returned from the login API—no typos, extra spaces, or missing characters.
- Error Handling: Always check the
errorfield in the response before accessingcourse_listto avoid unexpected null errors.
内容的提问来源于stack exchange,提问作者PRASHANT KARELIYA

