前端學習-flutter學習-006-包管理

ayubene發表於2024-07-09

《Flutter實戰·第二版》

簡介

類似node的npm
配置檔案是pubspec.yaml
name:應用或包名稱。
description: 應用或包的描述、簡介。
version:應用或包的版本號。
dependencies:應用或包依賴的其他包或外掛。
dev_dependencies:開發環境依賴的工具包(而不是flutter應用本身依賴的包)。
flutter:flutter相關的配置選項。

name: flutter01
description: "A new Flutter project."
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter 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 is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=3.4.3 <4.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^3.0.0

# 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 packages.
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

  # 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

示例(依賴Pub倉庫)

在pubspec.yaml中增加,並且點選右上角的Pub get 按鈕,會新增新的依賴

dependencies:
  flutter:
    sdk: flutter
  # 新新增的依賴
  english_words: ^4.0.0

在使用時,則需要引入包import 'package:english_words/english_words.dart';

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

// import 'package:flutter/cupertino.dart';
// void main() {
//   runApp(const MyApp());
// }

void main() => runApp(const MyApp());
// void main() => runApp(CupertinoApp(home: CupertinoTestRoute()));

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      initialRoute:"/", //名為"/"的路由作為應用的home(首頁)
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      routes:{
        "new_page":(context) => TipRoute(text:'這個引數是配置路由傳過來的'),
        "/":(context) => RouterTestRoute(), //註冊首頁路由
      },
    );
  }
}

class TipRoute extends StatelessWidget {
  TipRoute({
    Key? key,
    required this.text,  // 接收一個text引數
  }) : super(key: key);
  final String text;

  @override
  Widget build(BuildContext context) {
    //獲取路由引數
    var args=ModalRoute.of(context)?.settings.arguments;
    print('舊頁面傳遞引數的方法2:arguments:$args');
    return Scaffold(
      appBar: AppBar(
        title: Text("提示"),
      ),
      body: Padding(
        padding: EdgeInsets.all(18),
        child: Center(
          child: Column(
            children: <Widget>[
              Text(text),
              ElevatedButton(
                onPressed: () => Navigator.pop(context, "這個資料是新頁面傳遞給舊頁面的"),
                child: Text("返回"),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class RouterTestRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("初始頁面"),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () async {
                // 開啟`TipRoute`,並等待返回結果
                // var result = await Navigator.push(
                //   context,
                //   MaterialPageRoute(
                //     builder: (context) {
                //       return TipRoute(
                //         // 路由引數
                //         text: "這個資料是舊頁面傳遞給新頁面的",
                //       );
                //     },
                //   ),
                // );
                var result = await Navigator.pushNamed(context, "new_page",  arguments: "hi");
                //輸出`TipRoute`路由返回結果
                print("路由返回值: $result");
              },
              child: Text("開啟提示頁"),
            ),
            RandomWordsWidget(),
          ],
        ),
      ),
    );


  }
}

class RandomWordsWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 生成隨機字串
    final wordPair = WordPair.random();
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text('這是隨機的英文字串:' + wordPair.toString()),
    );
  }
}

其他依賴方式

  • 依賴本地包 路徑可以是相對的,也可以是絕對的。
dependencies:
	pkg1:
        path: ../../code/pkg1
  • 依賴Git:依賴儲存在Git倉庫中的包。
// 如果在倉庫根目錄中
dependencies:
  pkg1:
    git:
      url: git://github.com/xxx/pkg1.git
// 如果不在倉庫根目錄中
dependencies:
  package1:
    git:
      url: git://github.com/flutter/packages.git
      path: packages/package1      

相關文章