flutter / website

Flutter documentation web site
https://docs.flutter.dev
Other
2.72k stars 3.15k forks source link

Create an Album class shows dead code #10479

Closed RitchieP closed 2 weeks ago

RitchieP commented 2 weeks ago

Page URL

https://docs.flutter.dev/cookbook/networking/send-data

Page source

https://docs.flutter.dev/cookbook/networking/send-data#create-an-album-class

Describe the problem

When trying to follow the code for this page. I receive a dead code from VS code. Starting from this line at Create an Album class:

return switch (json) {

It looks like dart doesn't allow returning a switch like that.

Please let me know if there's anything more required from my side. Appreciate any help in advance!

Expected fix

No response

Additional context

No response

I would like to fix this problem.

sfshaza2 commented 2 weeks ago

@domesticmouse, can you take a look?

domesticmouse commented 2 weeks ago

@RitchieP can you please supply a minimal reproduction case? Dart switch expressions can definitely be used as the input to a return statement. However, switch statements cannot.

From your supplied code sample I cannot tell which you are coding. I'm guessing the statement version.

domesticmouse commented 2 weeks ago

A useful resource that explains using switch expressions for decoding JSON is our Dive into Dart's patterns and records codelab. Here's some code from the codelab showing a switch expression being used with a return statement.

String formatDate(DateTime dateTime) {
  final today = DateTime.now();
  final difference = dateTime.difference(today);

  return switch (difference) {
    Duration(inDays: 0) => 'today',
    Duration(inDays: 1) => 'tomorrow',
    Duration(inDays: -1) => 'yesterday',
    Duration(inDays: final days, isNegative: true) => '${days.abs()} days ago',
    Duration(inDays: final days) => '$days days from now',
  };
}
domesticmouse commented 2 weeks ago

I tested the code listed on the linked page in DartPad.dev and it looks like it works fine to me. Here's the code sample I put together from the recipe:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Album> createAlbum(String title) async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );

  if (response.statusCode == 201) {
    // If the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // If the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}

class Album {
  final int id;
  final String title;

  const Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': String title,
      } =>
        Album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}

void main() async {
  var album = await createAlbum('this is a tribue');
  print('Title of album: ${album.title}');
}

I'm curious what version of Dart and Flutter you have? This is a Dart 3.0 feature. Can you run the following command and show us the output?

$ flutter doctor -v
RitchieP commented 2 weeks ago
class Audio {
  final String text;

  const Audio({required this.text});

  factory Audio.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'text': String text
      } => Audio(text: text),
      _ => throw FormatException('Unexpected JSON type'),
    };
  }
}

This is my sample I'm trying to code. VS Code is telling me that after the return keyword, it is a dead code as below. image

And the follow is my output from $ flutter doctor -v

[√] Flutter (Channel stable, 3.19.5, on Microsoft Windows [Version 10.0.22631.3447], locale en-US)
    • Flutter version 3.19.5 on channel stable at C:\Users\user\Documents\Google\flutter_windows_2.8.1-stable\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 300451adae (5 weeks ago), 2024-03-27 21:54:07 -0500
    • Engine revision e76c956498
    • Dart version 3.3.3
    • DevTools version 2.31.1

[√] Windows Version (Installed version of Windows is version 10 or higher)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    • Android SDK at C:\Users\user\AppData\Local\Android\sdk
    • Platform android-34, build-tools 33.0.1
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.5.1)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
    • Visual Studio Community 2022 version 17.5.33424.131
    • Windows 10 SDK version 10.0.22000.0

[√] Android Studio (version 2020.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[√] IntelliJ IDEA Community Edition (version 2021.2)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.1
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[√] VS Code (version 1.79.2)
    • VS Code at C:\Users\user\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.66.0

[√] VS Code (version 1.89.0-insider)
    • VS Code at C:\Users\user\AppData\Local\Programs\Microsoft VS Code Insiders
    • Flutter extension version 3.86.0

[√] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.22631.3447]
    • Chrome (web)      • chrome  • web-javascript • Google Chrome 124.0.6367.92
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 124.0.2478.67

[√] Network resources
    • All expected network resources are available.
RitchieP commented 2 weeks ago

I tested the code listed on the linked page in DartPad.dev and it looks like it works fine to me. Here's the code sample I put together from the recipe:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Album> createAlbum(String title) async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );

  if (response.statusCode == 201) {
    // If the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // If the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}

class Album {
  final int id;
  final String title;

  const Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': String title,
      } =>
        Album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}

void main() async {
  var album = await createAlbum('this is a tribue');
  print('Title of album: ${album.title}');
}

I'm curious what version of Dart and Flutter you have? This is a Dart 3.0 feature. Can you run the following command and show us the output?

$ flutter doctor -v

Even when I copy pasted the whole code sample into my editor, it still shows me a dead code error after the return keyword.

parlough commented 2 weeks ago

Thanks for the extra details!

Perhaps your code is being analyzed with an earlier language version. What does the pubspec.yaml file of the project you're editing have in it? Particularly the SDK constraints/bounds.

RitchieP commented 2 weeks ago

Is this line the issue in my pubspec.yaml?

environment:
  sdk: '>=2.18.6 <3.0.0'

This is the full pubspec.yaml minus the dependencies, which I think is not relevant to solve this issue.

name: verbalex
description: A new Flutter project.

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: '>=2.18.6 <3.0.0'

dependencies:
  flutter:
    sdk: flutter

  # Dependencies goes down here, which I did not show cause it might be too long.

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^2.0.0

flutter:
  uses-material-design: true
parlough commented 2 weeks ago

Ah, thanks for the details @RitchieP!

environment:
  sdk: '>=2.18.6 <3.0.0'

Yes, this is the issue. A lower bound of >= 2.18.6 results in your project using a default language version of Dart 2.18. This syntax, switch expressions, are first supported with a language version of 3.0.

To use switch expressions and other newer features, you'll need to increase the lower bound to at least 3.0:

environment:
  sdk: ^3.0.0

Note there have been a few minor breaking changes in recent language versions. If you hit them, you can learn about them and find more resources for each release at https://dart.dev/guides/language/evolution.

Please let us know if the issue persists after updating your SDK constraint. Thanks again!