flutter 使用 Widget

main.dart 完整代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new Scaffold(
        body: new Center(
          child: new RandomWords(),
        ),
      ),
    );
  }
}

class RandomWords extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new RandomWordsState();
  }
}

class RandomWordsState extends State<RandomWords> {
  final wordPair = new WordPair.random();
  @override
  Widget build(BuildContext context) {
    return new Text(wordPair.asPascalCase);
  }
}

将上面的代码拆分成多文件。

项目 - lib - main.dart
项目 - lib - widgets - RandomWords.dart

将 RandomWords 相关的代码移到 RandomWords.dart 里面。

main.dart 代码:

import 'package:flutter/material.dart';
import './widgets/RandomWords.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new Scaffold(
        body: new Center(
          child: new RandomWords(),
        ),
      ),
    );
  }
}

RandomWords.dart 代码:

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

class RandomWords extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new RandomWordsState();
  }
}

class RandomWordsState extends State<RandomWords> {
  final wordPair = new WordPair.random();
  @override
  Widget build(BuildContext context) {
    return new Text(wordPair.asPascalCase);
  }
}