Flutter 上手攻略 (下)

1,523 阅读3分钟

前言: 在上一篇文章里,我介绍了怎么去搭建 Flutter 开发环境。那么这一篇文章里,我将会带大家使用 Flutter 编写一个 APP。 Flutter 使用的语言是 Dark,不是这文章的重点,不会作详解。另外,Flutter 是谷歌的移动 UI 框架,可以快速在 iOS 和 Android 上构建高质量的原生用户界面。

使用 Android Studio 创建项目

我这里使用 Android Studio 创建项目, 当然也可以用 VS Code,都是一样,看个人习惯。

  1. File -> New -> New Flutter Project

Snip20200715_3.png

  1. Flutter Application

Snip20200715_8.png

  1. APP 设置

Snip20200715_9.png

4.包名,最后 Finish 创建项目

Snip20200715_10.png

项目文件结构介绍

Snip20200715_11.png

Lib 目录

就是我们存放代码的地方,main.dart 是入口文件。

Main 代码分析

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // 此 widget 是应用程序的入口,继承 StatelessWidget 与 StatefulWidget 的 widget 都是 build 方法开始
  @override
  Widget build(BuildContext context) {
    // MaterialApp 是 android 风格的 App 入口,当然我们也可以用 iOS 风格的 CupertinoApp.
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // 主题
        primarySwatch: Colors.blue,
        // 视觉密度
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      // 启动的首页
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
// ... 后面的我们先不看,等下都要删掉。

Pubspec.yaml 配置文件分析

// name 很重要,如果修改了 name 所有的 dart 的文件的 import 前引用的本地文件包名都需要修改。要注意的是,手机显示的 APP 名字,不是在这里修改,必须在 iOS 和 Andriod 项目原生文件上修改才有作用。
name: flutter_app
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
// 软件版本号
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"


dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  // 在这里添加第三方 packages 的库文件,^表示适配和当前大版本一致的版本,~表示适配和当前小版本一致的版本, flutter get 下载。
  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
	# 添加资源,不单单是图片,images 是个和 pubspec.yaml 配置文件同级的目录,如果不同级,需要添加..
  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
	# 字体设置
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

最后,编译运行一下,看看能不能运行。

Snip20200715_16.png

如果能运行上面的画面,那么就证明运行成功了。

代码模块划分

Snip20200716_2.png

Assets 存放资源文件,比如图片,字体文件等

Common 存放一些公共的类,比如 api, values ,global 等

Models 存放数据模型类

Provide 存放状态管理

Routes 存放路由文件

Service 存放业务类,处理网络数据

Utils 存放工具类,比如 dio_manager, helper, sp_util 等

views 存放视图类, 里面按模块等划分

Main 是入口文件

底部 Tabbar

Snip20200716_4.png

如上图,我们要做的效果是这样的,点下面 ''设备''时切换设备页面,点“我”时切换我页面。

Snip20200716_5.png

如上图,在项目文件 views 里添加 homemine 文件夹与文件 home.dart 与 mine.dart 还有 root.dart

Main.dart 修改启动页

import 'package:defensor/views/root.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Defensor',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      // 这里修改 Root 为启动页
      home: Root(),
    );
  }
}

Root.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'home/home.dart';
import 'mine/mine.dart';

class Root extends StatefulWidget {
  @override
  _RootState createState() => _RootState();
}

class _RootState extends State<Root> {
  final List tabPages = [Home(), Mine()];
  int selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _dialogExitApp,
      // Scaffold 快捷脚手架做页面, bottomNavigationBar 可以设置底部导航栏
      child: Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('设备'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.account_box),
              title: Text('我'),
            ),
          ],
          onTap: (index){
            setState(() {
              this.selectedIndex = index;
            });
          },
          currentIndex: selectedIndex,
        ),
        body: tabPages[selectedIndex],
      ),
    );
  }

  /// 单击提示退出
  Future<bool> _dialogExitApp() {
    return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          content: Text("是否退出"),
          actions: <Widget>[
            FlatButton(onPressed: () => Navigator.of(context).pop(false), child:  Text("取消")),
            FlatButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("确定"))
          ],
        ));
  }
}

Home.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar 是上部导航栏
      appBar: AppBar(title: Text('设备')),
      // body 是主体内容
      body: Center(
        child: Text('设备'),
      ),
    );
  }
}

Mine.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Mine extends StatefulWidget {
  @override
  _MineState createState() => _MineState();
}

class _MineState extends State<Mine> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('我')),
      body: Center(
        child: Text('我'),
      ),
    );
  }
}

至此,以上基本已经搭建好一个基本 Flutter APP 了。当然,这里还有很多东西,比如路由类的封装,网络工具类的封装等等。这些都要一步一步完善起来。


  • 原创文章,转发请注明,谢谢~