Comments (9)
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!
from website.
@domesticmouse, can you take a look?
from website.
@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.
from website.
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',
};
}
from website.
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
from website.
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.
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.
from website.
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.
from website.
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.
from website.
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
from website.
Related Issues (20)
- Migrate Jekyll `include` to liquidjs `render` where possible
- Add missing setting to 'Deprecated imperative apply of Flutter's Gradle plugins' page
- Add title to interactive iframe
- Add Skip to Main Content link
- Fix clipped text in footer in responsive design
- Fix descriptions for Visit <page> links
- Clarify use of certain buttons and links
- Fix list structures
- Silence arrow icons in dropdown menus
- Fix colors in search results page footer
- Fix color contrast in search results
- Verbalize current page of search results pagination
- Fix verbalization of Flutter logos in search results page
- Fix focus in search results sort by dropdown menu
- Add role to search results sort by button
- Contain all page content in landmarks
- Make DartPad example button accessible using keyboard
- Enable verbalization of each line in embedded DartPad
- [web] Link to Medium post about optimizing Flutter load times
- [PAGE ISSUE]: 'Building user interfaces with Flutter' HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from website.