Flutter learning -First App

I followed the official website Write your first Flutter app practice again.
part1: the Write your First Flutter App
part2: https://codelabs.developers.google.com/codelabs/first-flutter-app-pt2/#8
complete project GitHub Address: https://github.com/skykywind/First- Flutter-App.git

First App

The development of this project will have a general understanding of the Flutter development, then you can better learn other details.
Statement about herein, this is not to take you step by step to achieve this example, because the official website is more suitable to follow to achieve. The purpose of my writing this is to summarize some of the basics of this project used.

The official website will achieve a simple App a name for the new company function, we will introduce a english_wordsthird-party library to generate name, drag, scroll down view, will generate more new names. Part2 will be added to the collection function, click the navigation button, you can jump to a new page to view the collection.
[Picture upload failed ... (image-a261bf-1559544689565) ]

Create a project

I use the Android Studio IDE,

  1. Select File> New Flutter Project;
  2. Project type selection Flutter application, then the next step;
  3. Modify Project name, project name must contain only lowercase letters and underscore confirm SDK path and Project location;
  4. Click finish, waiting created.

Code interpretation and analysis

Code Formatter

Android Studio / IntelliJ IDEA: Right-click in the coding region, selectReformat Code with dartfmt

The introduction of packet mode
  1. In the pubspec.yamlfile, add dependent libraries:
...
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: ^0.1.2

  #在这里引入 english_words
  english_words: ^3.1.0

dev_dependencies:
  flutter_test:
    sdk: flutter
...
  1. In calling file importimport:
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
On StatelessWidgetandStatefulWidget

Flutter all objects are abstract became Widget, such as the view component, Layout, App itself, are Widget:

  • StatelessWidget, all of its properties are immutable, modified with Final;
  • StatefulWidget, the life cycle, the state is likely to change. Achieve StatefulWidget, requires at least two categories:
    • A StatefulWidget class.
    • A State class. This class is to maintain the state of the Widget.
mainfunction

main.dartThe main function is the entry of the entire procedure:

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

main function is to run direct return MyApp () example, which is running our application.

What App that?
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Startup Name Generator',
      theme: ThemeData(
        primaryColor: Colors.deepPurpleAccent,
      ),
      home: RandomWords(),
    );
  }
}

We can see MyApp itself is a StatelessWidget, by buildconstructing the contents of the context method. Demo use this MaterialAppclass to build a Materialstyle of application. In addition MaterialApp, we can also use Cupertino Widgets , or Container, Centerlike as a content view.

MaterialAppHere called three attributes:

  • title: page title
  • theme: Theme Settings
  • home: page content, which is the portion other than navigation. Here is a StatefulWidget home of RandomWords class.
StatefulWidget use

StatefulWidget using the above-mentioned two categories, Widget itself and the State.

class RandomWords extends StatefulWidget {
  @override
  RandomWordsState createState() => RandomWordsState();
}

RandomWordsImplementation is very simple, just rewrite createState()method, bindings returned RandomWordsState.
Here is RandomWordsStatethe full code.

class RandomWordsState extends State<RandomWords> {
  final List<WordPair> _suggestions = <WordPair>[];
  final Set<WordPair> _saved = Set<WordPair>();
  final _biggerFont = const TextStyle(fontSize: 18.0);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Startup Name Generator'),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.list), onPressed: _pushSaved),
        ],
      ),
      body: _buildSuggestions(),
    );
  }

  Widget _buildSuggestions() {
    return ListView.builder(
        padding: const EdgeInsets.all(16.0),
        itemBuilder: (context, i) {
          if (i.isOdd) return Divider();

          final index = i ~/ 2;
          if (index >= _suggestions.length) {
            _suggestions.addAll(generateWordPairs().take(10));
          }

          return _buildRow(_suggestions[index]);
        });
  }

  Widget _buildRow(WordPair pair) {
    final bool alreadySaved = _saved.contains(pair);
    return ListTile(
      title: Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
      trailing: Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }

  void _pushSaved() {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (BuildContext context) {
        final Iterable<ListTile> tiles = _saved.map(
          (WordPair pair) {
            return ListTile(
              title: Text(
                pair.asPascalCase,
                style: _biggerFont,
              ),
            );
          },
        );

        final List<Widget> divided = ListTile
            .divideTiles(
              context: context,
              tiles: tiles,
             )
            .toList();

        return Scaffold(
          appBar: AppBar(
            title: Text('Saved Suggestions'),
          ),
          body: ListView(children: divided),
        );
      },
    ),);
  }
}

The code looks a lot, but actually a few ways:

  1. Widget build(BuildContext context)Way to create a navigation head. ScaffoldCreating a top navigation section, add a title and a picture button, push the button click event to the next page (_pushSaved () method);
  2. Widget _buildSuggestions()Method creates a ListView, Widget _buildRow(WordPair pair)way to create ItemBuilder for the ListView.
  3. _suggestionsAll recommendations generated by the store name, _savedsave all your favorite name.
to sum up

Demo a whole allows us to embrace each step of the development and profile of Flutter App, which is realized in the form of Widget assembly of pages, each component will have its own attributes can be customized.
In addition, this Demo we also learned how to introduce third-party packages, how to use StatelessWidgetand StatefulWidget. Material style

Guess you like

Origin blog.csdn.net/weixin_34293141/article/details/90916403
Recommended