LoginSignup
2
0

debugPrintを活用する

Posted at

はじめに

個人開発でQiitaアプリを制作しています。
マイページを作成していましたが、ユーザの情報がなかなか表示されずに困ってしまいました。

内容は、仮置きで置いている状態です⬆️

修正前のソースコード(一部抜粋)

スクリーンショット 2024-04-07 23.09.43.png

解決策:dubugPrintをひたすら出力させる

何が原因なのか、dubgPrintを使用して探ることにしました。
以下のコードのようにdubugPrintを加えました。⬇️

 static Future<User> fetchAuthenticatedUserInfo() async {
    final accessToken = await _getAccessToken(); // アクセストークンを取得するメソッド
    debugPrint('Fetched access token: $accessToken'); // ログ出力でトークン確認


    final url = Uri.parse('${Urls.qiitaBaseUrl}/authenticated_user');
    debugPrint('Requesting authenticated user info from: $url'); // リクエストURLのログ

    final response = await http.get(url, headers: {
      'Authorization': 'Bearer $accessToken'
    });
    debugPrint('Received response: ${response.body}'); // レスポンス内容のログ

    if (response.statusCode == 200) {
      final Map<String, dynamic> jsonResponse = jsonDecode(response.body);
      return User.fromJson(jsonResponse);
    } else {
      debugPrint('Error fetching user info: ${response.statusCode}');
      throw Exception(_exceptionMessage(response.statusCode));
    }
  }

static Future<String> _getAccessToken() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String? accessToken = prefs.getString('accessToken');

  // アクセストークンの存在をログで確認
  debugPrint('Access token from SharedPreferences: $accessToken');

  if (accessToken == null || accessToken.isEmpty) {
    debugPrint('Access token is null or empty');
    throw Exception('No access token found');
  }
  return accessToken;
}

出力結果

上記の内容においてのdubugPrint出力結果⬇️

スクリーンショット 2024-04-07 23.07.34.png

上記の内容を要約すると、以下のようになります。

  • ログインした人のアクセストークン→⭕️取り出せている
  • ログインした人の情報→❌出力されていない
    「Failed to fetch user info: type 'Null' is not a subtype of type 'String' in type cast」と言われてしまっています。

つまり、nullの値が与えられているのに、nullの値が許容されていないString型に無理やり変換しようとしています。
修正するにはnullの値を許容できるようにする必要があります。
以下のようにコードを修正してみました。

修正後のソースコード(一部抜粋)

スクリーンショット 2024-04-07 23.12.31.png

無事に解決

上記のようにコードを修正したら無事にマイページにユーザ情報を取得できました。⬇️

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0