這是一個跨端的時代,各種跨端框架你方唱罷我登場,今天小編帶領大家來入門Flutter,看它到底有沒有傳說中的那么好。磨刀不誤砍柴工,先來安裝Flutter開發環境吧。先安裝Android Studio,然后在Settings->Plugin里選擇 Browser Repositories,在線安裝Flutter插件。安裝Flutter插件時,它會提示自動安裝Dart語言插件。

安裝插件
插件安裝好后,需要再去Flutter中文官網下載SDK(比英文官網下載速度快很多),根據官網要求設置好Flutter Path及Git Path的系統環境變量。然后在命令行窗口輸入flutter doctor命令,它會自動關聯下載Dart SDK,如果發現下載比較慢,可以將FLUTTER_STORAGE_BASE_URL和PUB_HOSTED_URL兩個網址映射到中文站,并添加到系統環境變量里。flutter doctor多次運行后,會看到提示小編的android studio版本太低(我的是2.3版本,而flutter要求3.0版本以上),倒霉了,得升級android studio,差不多1個G,可夠我下載的了,先去泡杯咖啡,再繼續。

flutter doctor命令

檢查結果
新版android studio安裝好后,按照最開始的步驟,在settings->plugins菜單里安裝flutter 和 dart插件,然后就可以在File菜單開始New一個flutter的Project啦!

new flutter project
工程建好后,我們可以看到 flutter app的代碼是用Dart語言編寫的,語法與Java非常類似,幾乎沒有什么新的學習成本。從MyApp的代碼來看,我們可以知道flutter里的界面都是用Widget來搭建的,這一點與Android不同,后面小編再帶大家細細品味Widget。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Hello World!'),
);
}
}
運行后,我們在安卓模擬器里可以看到flutter程序順利的跑在了android系統里了,無需做任何android的代碼移植,天生支持android。當然它也天生支持iOS,這就是我們第一個跨端app!
原文地址:https://www.toutiao.com/a6923177941820031496/