Dart 常见问题和解答

Updated June 2019

This page collects some of the top questions we’ve heard from the communitysince Dart was open sourced.

General

Q. Is there a specification for Dart?

Yes. Dart 1 has a formal specification owned by Ecma TC52.

Dart 2.x is currently being specified; the specification is available from theDart language specification page.

Q. How are you taking input on changes to Dart?

We listen to feedback and issues, and we review patches from contributors.A contributor with a good track record can become a committer to the repository.Google engineers will also be working in the public repository, making visiblechanges. The project is lucky to have received many external patches and haswelcomed distributed committers.


Language

Q. Isn’t Dart a lot like Java?

Dart has some similarities with Java. See the Intro to Dart for JavaDeveloperscodelab for examples of some of the differences between Dart and Java.

Q. How does Dart relate to Go?

Dart and Go are both language projects started at Google, but theyare independent and have different goals. As a result,they make different choices, and the languages have very differentnatures, even while we all try to learn from each others’ work.

Q. Why isn’t Dart more like Haskell / Smalltalk / Python / Scala / other language?

Various reasons, depending on the language being asked about.

For languages that are quite different from JavaScript: it’s important for Dartto compile to efficient JavaScript. Our experience in GWT is that if the sourcelanguage is too different from JavaScript, it creates some cases where complexoutput code is needed to emulate the source language’s behavior. This can causeperformance to vary in ways that are not transparent to the programmer.

For languages that are compiled to native code: it’s important that Dartcompiles efficiently to machine code, and thus it shares a number of aspectswith other compiled languages.

For languages that are “more dynamic” than Dart: Dart deliberately trades offsome of this arbitrary runtime modification for the goal of better performanceand more productive tools.

Q. Why isn’t Dart syntax more exciting?

We did throw in some nice syntactic features such as this. constructor argsand => for one-line functions, but we’d agree that Dart choosesfamiliarity over excitement. One team member’s personal testimonial:“I wish it had a little more razzle dazzle but I can’t deny thatliterally on my first day of writing Dart code, I was productive in it.”

Q. Does Dart have reflection capabilities?

For servers and command-line scripts, we have reflection support from themirrors API.There is no support for mirrors when using Dart to write web orFlutter apps (more info).

Q. Can Dart add tuples, pattern matching, non-nullable types, partial evaluation, optional semicolons, …?

Future releases might be able to include (some of) those features, althoughwe can’t include everything. Some features don’t fit the basic nature of thelanguage, and some don’t play well with other features. Simplicity is the singlemost important gift we can give to future programmers.

Please look at the language funnel andlanguage issues list to see if your request is already there.If it is, let us know that you care and give it a thumbs up. Otherwise, go aheadand add a new request issue (see the language evolution processfor details). Make a thoughtful argument for your feature. Sample code with andwithout your feature is good evidence; a sizeable codebase that shows the needis even better evidence.

Don’t be surprised if the Dart language team says “no” by default.It’s far more painful to remove a language feature than to add it, soDart is likely to add the most obvious features first, and then revisit the nexttier later. And there simply are more possible language features in the worldthat can fit into any single language without making a total hash of it. Butwe do very much appreciate suggestions and evidence. We hope you’ll see ourappreciation through careful design choices and fair communication about them.


Types

Q. Is Dart a statically typed language?

Yes, Dart 2 is statically typed. For more information,read about Dart’s type system.

With its combination of static and runtime checks, Dart has a sound type system,which guarantees that an expression of one type cannot produce a value ofanother type. No surprises!

Even with type-safe Dart, you can annotate any variable withdynamic if you need the flexibility of a dynamic language.The dynamic type itself is static, but can contain any type at runtime.Of course, that removes many of the benefits of a type-safe languagefor that variable.

Q. Why are generics covariant?

Covariant generics fit a common intuition that programmers have, and very oftenthis intuition is correct, such as in the common “read-only” use of a generic.Although this intuition isn’t always correct, Dart is erring on the side ofconvenience by having covariant generics.

The only other reasonable default variance would be invariance. While havingonly invariant generics would definitely prevent more errors, it would alsoprevent a lot of valid programs or require conversion every time you have a listof “apples”, and someone just wants “fruits”.

We are familiar with a variety of ways that languages try to mark or infervariance. We feel that variance inference systems add too much complexity fortheir benefit in Dart.

Again, we’re trying to be pragmatic, and we think the outcome is reasonable.


Usage and tools

Q. Does Dart support JSON?

Yes. See the JSON converters in the dart:convert library.

Q. Can Dart run on the server?

Yes. See Dart on the Server for details.

Q. How do I use third party code, or share code?

You can find many packages on the pub.dev site a service for hostingpackages of Dart code. Use the pub command to package your code and uploadto the site.

Q. Do I need to use a particular editor or IDE to write Dart code?

Nope. You can try out Dart code with DartPad, and then use your favoriteeditor or IDE for development. Some full-featured IDEs such as IntelliJ IDEA,WebStorm, and Visual Studio Code have Dart plugins. Open source Dart pluginsalso exist for a number of editors. For more information, see the Dart tools.

Q. Can I build an Android app with Dart?

Yes! You can build an Android app that also works on iOS from a single codebaseusing Flutter, which is powered by the Dart platform.

Q. What are some real-world production deployments of Dart?

Google AdWords, AdSense, AdMob, and the Google Assistant all use Dart.A significant portion of Google’s revenue flows through these apps.Inside or outside of Google, every Flutter app uses Dart.


Native execution

Q. Can I compile Dart code to native code?

Yes. For programs targeting devices (mobile, desktop, server, and more), DartNative includes both a Dart VM with JIT(just-in-time) compilation and an AOT (ahead-of-time) compiler for producingmachine code.

Flutter is a sample framework that uses Dart’s native compilation capabilityto produce fast native apps.

Q. Can I compile a Dart program for running in a terminal?

Yes. Dart programs can be compiled to native x64 machine code for running in aTerminal/Command Prompt on desktop operating systems such as Windows, macOS, andLinux. For more details, see the dart2native documentation.

Q. Which is faster — AOT- or JIT-compiled code?

Code that’s compiled ahead-of-time (AOT) with a compiler such as dart2nativehas different performance characteristics fromcode that’s compiled just-in-time (JIT) in the Dart VM.AOT-compiled code is guaranteed to have fast startup and consistent runtimeperformance, with no latency during early runs. JIT-compiled code is slower atstartup, but it can have better peak performance after it runslong enough for runtime optimizations to be applied.


Web: general

Q. What browsers do you support as JavaScript compilation targets?

The production compiler (dart2js) supports Internet Explorer 11and the last two major releases of the following browsers:

  • Chrome
  • Edge
  • Firefox
  • Safari

The development compiler (dartdevc) supports only Chrome.

Q. Is Dart supported by my browser?

Although no production browsers can execute Dart code directly,all modern browsers can execute Dart code that’s been compiled to JavaScript.

Q. How do I debug an app?

For setup details and a walkthrough, see Debugging Dart Web Apps.

The debugging section of the dart2js documentationhas some tips for specific browsers.

Q. What web frameworks can I use with Dart?

You can use the low-level HTML API defined by core libraries such as dart:html,or you can use a framework such as AngularDart.During Google I/O 2019 we announced a technical preview ofFlutter for web that lets you take Flutter UI code and business logicand run it directly in the browser.

Q. Will the Dart VM get into Chrome?

No.Dart is designed to compile to JavaScript to run across the modern web.


Web: JavaScript and other technologies

Q. How does Dart code interoperate with JavaScript libraries?

Although Dart and JavaScript are completely separate languages withseparate VMs, they can interoperate. For more information, seeJavaScript and TypeScript interop.

Q. I have a large JavaScript codebase. How can I migrate it to Dart?

Try migrating one major feature at a time, and use theJavaScript interoperability libraryonly when necessary.

Q. How does Dart compare with using the Closure compiler on JavaScript?

The idea of optional type annotations is similar.Dart’s are nicer syntactically.

Compare the following Closure compiler code:

  1. // Closure compiler code
  2.  
  3. /**
  4. * @param {String} name
  5. * @return {String}
  6. */
  7. makeGreeting = function(name) {
  8. /** @type {String} */
  9. var greeting = 'hello ' + name;
  10. return greeting;
  11. }

With the following Dart code:

  1. // Dart code
  2.  
  3. String makeGreeting(String name) {
  4. var greeting = 'hello $name';
  5. return greeting;
  6. }

Q. How does Dart compare with CoffeeScript?

Both Dart and CoffeeScript are inspired by JavaScript, and both can betranslated back to it. They make different choices, particularly in the flavorof their syntax. As a language we think it’s fair to say that Dart differssemantically from JavaScript more than CoffeeScript does; that may result in aless line-for-line translation, but we believe Dart-generated JavaScript canhave excellent size and speed.

Dart introduces new semantics, while CoffeeScript retains the semanticsof JavaScript.

If you like CoffeeScript for its more structured feel than raw JavaScript, youmay like Dart’s static type annotations.

Q. What does Google think of TypeScript?

TypeScript and Dart have similar goals; they make building large-scale webapps easier. However, their approaches are fairly different. TypeScriptmaintains backwards compatability with JavaScript, whereas Dart purposely made abreak from certain parts of JavaScript’s syntax and semantics in order toeradicate large classes of bugs and to improve performance. The web has sufferedfrom too little choice for too long, and we think that both Dart and TypeScriptare pointing to a brighter future for web developers. You can read amore complete response on our blog.

Q. I have a large app written in GWT. How do I port it to Dart?

Java and Dart are syntactically similar,so this might be easier than you think.You can rely on the Dart analyzerto flag any syntax problems. Alternatively, you mayconsider porting one feature at a time to Dart and using theJavaScript interoperability library as the common middleground. Be sure to watch Dart-JavaScriptinteroperability,a talk from Dart Developer Summit 2016.


Web: JavaScript compilation

Q. Will any valid Dart code compile to JavaScript, or are there limitations?

We intend for any valid Dart code to compile to JavaScript. Of course,some libraries only run on the server or in Flutter.For example, the dart:io libraryprovides access to operating system files and directories with APIs notavailable to the browser.

Q. Why does Dart have two JavaScript compilers, dartdevc and dart2js?

The two compilers have different use cases. You don’t usually have to worryabout which compiler you’re using, because the webdev toolchooses the right compiler for your use case. When you’re developing your app,webdev chooses dartdevc, which supports incremental compilation soyou can quickly see the results of your edits.When you’re building your app for deployment, webdev chooses dart2js,which uses techniques such as tree shaking to produce optimized code.

Q. How can dart2js produce JavaScript that runs faster than handwritten JavaScript?

Think of dart2js as a real compiler,which can analyze your entire program and make optimizationsthat you probably can’t or won’t do. Just like gcc can output efficient codeby moving code around, dart2js can take advantage of Dart’s structured natureto implement global optimizations.

We don’t claim that all Dart code will run fasterthan handwritten JavaScript, when compiled to JavaScript,but we’re working to make the common cases fast.

Q. How can I write Dart code that compiles to performant JavaScript?

See Helping dart2js generate bettercode.Just be aware that this information might change as the implementation ofdart2js changes.

Q. Why is the code for “Hello, World” so big, compared to the original Dart code after compilation to JavaScript?

We believe that it’s important to create small and efficient JavaScriptfrom Dart, but most developers don’t write “Hello, World” apps. It’s allrelative, and with tree shaking (dead code elimination), minification, andcompression, Dart apps can be compiled to JavaScript fairly efficiently.

Kevin Moore saw improvements in the size of the generatedJavaScript from his real-world HTML5 game.

The dart2js team strives to generate smaller output, but is more focused onreal-world apps instead of trivial examples.

Q. How are floating point numbers handled when compiled to JavaScript?

JavaScript has only one number representation: an IEEE-754 double-precisionfloating-point number. This means that any number—integer or floatingpoint—is represented as a double. JavaScript has typed data arrays,and the mapping from native Dart typed lists to JavaScript typed arrays is trivial.

Q. How are integers handled when compiled to JavaScript?

Because all numbers are stored as doubles,integers are restricted to a 53-bit precision.Integer values in the range of -253 to 253 can be storedwithout loss of accuracy.Because JavaScript VMs play trickswith the internal representation of numbers(similar to those described above),staying within smi range is still good practice.

Q. How are typed lists handled when compiled to JavaScript?

JavaScript offers typed arraysthat are compatible with Dart’s typed lists.The mapping is trivial—for example,Float32List becomes a Float32Array.The one exception today is that dart2js does not support 64-bit integersand thus does not support Int64List or Uint64List.Dart code compiled via dart2js results in a runtime exceptionif either of those lists is used.

Q. Why not compile Dart to asm.js instead of JavaScript?

Asm.js is a very restricted subset of JavaScript best suited as a compilationtarget for C compilers. It does not include JavaScript objects or directaccess to the DOM. Essentially, it allows only arithmetic operations andmanipulations on typed arrays.

While it is possible to implement the features that Dart requires,they would incur a large overhead in both speed and size, compared torelying on the already existing features provided by the underlyingJavaScript engine.For example, any JavaScript machine comes with a garbage collector;implementing another one in asm.js would increase the output size, and benoticeably slower than the well-tuned garbage collectors ofmodern JavaScript VMs.