2021年9月22日 星期三

[flutter, package] How to use external package

How to use external package

井民全, Jing, mqjing@gmail.com

GitHub

TL;DR

This document shows you how to use external packages which are based on the doc here.

# Step 1: Install package: you can review the package on pub.dev

flutter pub add english_words 


# Step 2: Code

File: ./lib/main.dart

import 'package:english_words/english_words.dart';

final wordPair = WordPair.random(); // <<---- Create a compound word randomly

child: Text(wordPair.asPascalCase), //<---- show the WordPair


# Step 3: Run

flutter run


Table of contents

1. Install package 1

2. Usage 2

2.1. Code 2

2.2. Run 3

3. Result 3

4. References 4



1. Install package

flutter pub add $PACKAGE-NAME   # you can review the package on pub.dev.

Where

  • pub: the commands for managing Flutter packages 

Ex

Following command will install the english_words package to your project.

flutter pub add english_words


Check

File: pubspec.yaml

...

dependencies:

  flutter:

sdk: flutter

  cupertino_icons: ^1.0.2

  english_words: ^4.0.0

...


2. Usage

2.1. Code

File: ./lib/main.dart

import 'package:english_words/english_words.dart';

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget { // Create a widget that does not require mutable state

  @override

  Widget build(BuildContext context) { // Overwrite the build method

    final wordPair = WordPair.random(); // <<---- Create a compound word randomly

    return MaterialApp( // Create a App that uses material design

      title: 'Welcome to Flutter',

      home: Scaffold( // Apply the basic material layout

        appBar: AppBar(

          title: const Text('Welcome to Flutter'),

        ),

        body: Center(

          child: Text(wordPair.asPascalCase), //<---- show the WordPair

        ),

      ),

    );

  }

}

2.2. Run

flutter run

3. Result

4. References

  1. https://flutter.dev/docs/get-started/codelab

  2. English_words API

  3. Scaffold-class