The first Flutter demo - implementing an infinite loop list

The first Flutter demo (1)

Refer to the flutter official website to implement the first Flutter application. Part 1: Implementing an infinitely looping list

Function introduction of the first part:

Created a Flutter app from scratch;

  1. Write Dart code;
  2. Use an external third-party library (package);
  3. Tried hot reload during development;
  4. Implemented a stateful widget;
  5. A lazy loaded, infinite scrolling list is created.

Effect diagram:
insert image description here
All codes are in main.dart,
main.dart code is as follows:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: RandomWords(),
    );
  }
}

// #docregion RandomWordsState, RWS-class-only
class RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];
  final _biggerFont = const TextStyle(fontSize: 18.0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Startup Name Generator'),
      ),
      body: _buildSuggestions(),
    );
  }

  /*构造器:此方法构建显示建议单词对的 ListView*/
  Widget _buildSuggestions() {
    return ListView.builder(
        padding: const EdgeInsets.all(16.0),
        itemBuilder: (context, i) {
          /*1 偶数行会执行_buildRow添加单词;奇数行会添加分割线*/
          if (i.isOdd) {
            return Divider();
          }
          /*2*/
          final index = i ~/ 2; /*3*/
          if (index >= _suggestions.length) {
            _suggestions.addAll(generateWordPairs().take(10)); /*4*/
          }
          return _buildRow(_suggestions[index]);
        });
  }

  /*每行listview样式*/
  Widget _buildRow(WordPair pair) {
    return ListTile(
      title: Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
    );
  }
}

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

Complete project download link:
click to download

Guess you like

Origin blog.csdn.net/u011084603/article/details/103487998