从头学 Dart 第一集

172 阅读5分钟

最近打算自己做一个电商 App 调研之后选择技术栈为 Flutter 因此打算梳理一下 Flutter 的所有知识点,做个预热。

  1. 关于编译及平台
  • Whilst you can write the code for all platforms on the same machine, you can only test & run i0S & macos apps on macos machines, Windows apps on Windows machines and Linux apps on Linux machines!
  • Android and web apps can be built on all operating systems.
  1. 关于在安装 git 的时候选中其它 linux 命令 Use Gitand opfonal Unix tools from the Command Promp
  2. Flutter 安装步骤
    1. 参考这里 docs.flutter.dev/community/c…
    2. 进入官网 docs.flutter.dev/get-started…
    3. 下载稳定版本 flutter_windows_3.24.3-stable.zip
    4. 创建另存为的目录
    • The Flutter SDK should download to the Windows default download directory: %USERPROFILE%\Downloads.
    • Create a folder where you can install Flutter: Consider creating a directory at %USERPROFILE% (C:\Users{username}) or %LOCALAPPDATA% (C:\Users{username}\AppData\Local).
    • PS Expand-Archive –Path $env:USERPROFILE\Downloads\flutter_windows_3.24.3-stable.zip -Destination $env:USERPROFILE\dev\
    • 设置环境变量 %USERPROFILE%\dev\flutPS C:> flutter doctorter
    1. 安装 Android Studio
      1. 选择 Android Virtual Device
      2. 在 install type 中勾选 Custom
      3. 在 SDK Components Setup 中勾选全部(If “Android Virtual Device” is “unavailable” you can continue without it.)
      4. 安装完毕之后在 Welcome to Android Studio 页面的 more actions 中打开 SDK Manager
      5. 在 SDK Platform 选择 Android 13.0 (Tiamisu); 在 SDK Tools 选择 Android SDk Build-Tools 34.rc、Android SDk Command-line Tools(latest)、 Android Emulator Htypervisor Driver (installer)、 Android SDk Platform-Tools、 Andoid Emulator
      6. 在 Welcome to Android Studio 页面的 more actions 中打开 Virtual Device Manager 在 Select Hardware 的 Phone 中选择 Pixel 6 进行安装 并在 Select a system image 中选择 Tiramisu 在 Verify Configuration 中选择 Hardware-GLES 2.0
      7. 在桌面新建名为 flutter_projects 的目录,注意这个下划线是唯一合法的连接符, 在目录 cmd 中运行 flutter create first_app 创建新的项目
      8. 在 vscode 中安装 Flutter 插件
      9. 用 vscode 打开项目然后使用 ctrl+shift+p 打开命令行运行 Flutter: Launch Enmulator 并选择 Pixel 6 API 33 运行项目 (或者在 terminal 执行 fluteer run 命令)
      10. 在 lib/main.dart 中修改标题,看能够刷新成功,如果不成功点击模拟器上的闪电符号手动刷新。
  3. widget in flutter: widget are the ui building blocks you use in your flutter code to construct the app user interface. you'll learn all about them over the next lectures and sections! 其本质上是一个 tree 因此在 flutter 中具有一个 widget tree
  4. Material 组件库是 Flutter 重要的组件库,非常强大并且易于扩展,并且是官方的。搞不好是唯一一个 -- Google's flexible design system(highly customizable and extendable) 它的官方网址为 docs.flutter.dev
  5. Dart & Flutter 代码是从上往下 parsed 然后再 compiled 成原生的代码。
  6. 在开始之前我们需要将自动生成的 main.dart 中的代码删除干净并且确保 pubspec.yaml 文件中有如下代码(依赖):
dependencies:
   flutter:
      sdk: flutter
  1. Flutter app 启动步骤:main -> runApp()->pass a widget to runApp
  2. 顺序传参和命名传参:flutter 支持顺序传参,这没有什么可说的,命名传参如下所示:
void add({num1, num2}) {
   num1 + num2;
}

void demo() {
   add(num2: 5, num1: 3);
}
  1. 我们在 main.dart 中的代码总是这样的:
import 'package:flutter/material.dart';

void main() {
   runApp(MaterialAPP(home: Text()))
}

可以看出来组件总是以函数的方式进行使用的,home 是比较重要的配置项,而 Text 本身是一种组件,来自 Material。 11. 代码编辑器中的蓝色波浪下划线不是报错,而是表示不是最佳实践。 12. const helps Dart optimize runtime performance 但是 const 也不是越多越好,一般来说编辑器会提醒在什么时候进行添加。 13. 在页面上创建第一个文本组件:

import "package:flutter/material.dart";

void main(){
   runApp(const MaterialApp(home: Text('Hello World!')));
   // runApp(const MaterialApp(home: const Text('Hello World!')));
}

这里明显采用的是命名参数,并且 home 参数是必须的,而我们的文字也是以一种函数的方式产生的。 直接使用 Text 组件生成组件效果将会非常差,因此我们最好还是在最外层使用 Scaffold 组件:

void main(){
   runApp(const MaterialApp(home: Scaffold(body: Text('Hello World!'))));
}

我们给每个括号后面添加一个 comma 之后再使用命令 Format Document 格式化代码是非常便利的! 14. Dart 是一种类型安全的语言,在 Dart 中每一个 value 都具有至少一个类型,类似于 js 中的原型链,并且最后总会终结于 Object, 例如 'hello word' 就具有 String 和 Object 两个类型。 15. 常见的核心类型有:int double num String bool Object 16. 给 Scaffold 组件中添加背景色,可以写成这样:

void main() {
   runApp(   
      const MaterialApp(
         home: Scaffold(
            backgroundColor: Color.fromARGB(255,47,5,120),
            body: Center(
               child: Text('Hello World!'),
            ), //Center
         ), // Scaffold
      ), // MaterialApp
   );
}

核心代码如下所示:backgroundColor: Color.fromARGB(255,47,5,120) 17. 在 Flutter 中, Widgets 等价于 Objects 等价于 Data Structure in Memory -- all values are Object in the end! 18. 我们的文字想要排在屏幕中间因此在 body 之下 Text 之上我们需要使用 Container 组件协助定位:

void main() {
   runApp(   
      MaterialApp(
         home: Scaffold(
            body: Container(
               child: const Center(
                  child: Text('hello world!'), // Text
               ), // Center
            ), // Container
         ), // Scaffold
      ), // MaterialApp
   );
}

注意到 const 位置的变化,现在 MaterialApp 前面已经没有 const 了,原因在于 Container 是响应式的不是静态的,用 const 修饰不合适。 但是我们确实希望使用 const 对其加速,所以将 const 移动到了 Container 内部。 19. 使用 decoration 为 body 添加渐变色

void main() {
   runApp(   
      MaterialApp(
         home: Scaffold(
            body: Container(
               decoration: const BoxDecoration(
                  gradient: LinearGradient(
                     colors: [
                        Color.fromARGB(255, 26, 2, 80),
                        Color.fromARGB(255, 45, 7, 98),
                     ], 
                     begin: Alignment.topLeft,
                     end: Alignment.bottomRight,
                  ), // LinearGradient
               ), // BoxDecoration
               child: const Center(
                  child: Text('hello world!'), // Text
               ), // Center
            ), // Container
         ), // Scaffold
      ), // MaterialApp
   );
}

不难看出完成渐变色的要素为:BoxDecoration.gradient -> LinearGradient(colors, begin, end) 20. 上面我们调整了 Text 的位置,接下来我们调整 Text 的样式

child: const Center(
   child: Text(
      'hello world!',
      style: TextStyle(
         color: Colors.white,
         fontSize: 28.5,
      ), // TextStyle
   ), // Text
), // Center
  1. Dart is an object-oriented language 事实上,Dart 是最面向对象的语言;所有的类型分成两个大类 Primitive Values 和 More Complex Values 后者一般通过蓝图 class 创建。
  2. Object is created by calling the “constructor function" of a class 使用 class 我们可以方便的将固定的部分剥离开来,便于维护和复用
void main() {
   runApp(
      MaterialApp(
         home: Scaffold(
            body: GradientContainer(),
         ), // Scaffold
      ), // MaterialApp
   );
}

class GradientContainer extends StatelessWidget {
   @override
   Widget build(context) {
      return Container(
         decoration: const BoxDecoration(
            gradient: LinearGradient(
               colors: [
                  Color.fromARGB(255, 26, 2, 80),
                  Color.fromARGB(255, 45, 7, 98),
               ], 
               begin: Alignment.topLeft,
               end: Alignment.bottomRight,
            ), // LinearGradient
         ), // BoxDecoration
         child: const Center(
            child: Text('hello world!'), // Text
         ), // Center
      ), // Container
   }
}

Dart 中好像不需要使用 new 关键字就能完成 new 一个 Object 的过程。