赞
踩
基础步骤
第一步: 创建 Flutter app
第二步: 打开 /lib/main.dart,删除main.dart的所有代码,然后替换为下面的代码
第三步: 安装依赖程序 english_words
第四步: 启动应用
//导入包。 import 'package:english_words/english_words.dart'; import 'package:flutter/material.dart'; //文档 // https://flutter.cn/docs/get-started/codelab //应用入口。 void main() => runApp(MyApp()); //应用结构。 class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( //应用名称 title: '名称生成器', //白色主题 theme: new ThemeData( primaryColor: Colors.white, ), //应用首页路由 home: RandomWords(), ); } } //定义首页 class RandomWords extends StatefulWidget { const RandomWords({Key? key}) : super(key: key); @override //State类 _RandomWordsState createState() => _RandomWordsState(); } //State类 class _RandomWordsState extends State<RandomWords> { final _suggestions = <WordPair>[]; final Set<WordPair> _saved = new Set<WordPair>(); final _biggerFont = const TextStyle(fontSize: 18.0); Widget _buildSuggestions() { return ListView.builder( padding: const EdgeInsets.all(16.0), itemBuilder: (context, i) { if (i.isOdd) { return const 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: new Icon( alreadySaved ? Icons.favorite : Icons.favorite_border, color: alreadySaved ? Colors.red : null, ), onTap: () { setState(() { if (alreadySaved) { _saved.remove(pair); } else { _saved.add(pair); } }); }, ); } @override //构建UI界面 Widget build(BuildContext context) { //Scaffold 是 Material 库中提供的页面脚手架 //它提供了默认的导航栏、标题和包含主屏幕widget树的body属性 return Scaffold( appBar: AppBar( title: const Text("名称生成器"), actions: <Widget>[ new IconButton(icon: const Icon(Icons.list), onPressed: _pushSaved), ], ), body: _buildSuggestions(), ); } void _pushSaved() { Navigator.of(context).push( new MaterialPageRoute<void>( builder: (BuildContext context) { final Iterable<ListTile> tiles = _saved.map( (WordPair pair) { return new ListTile( title: new Text( pair.asPascalCase, style: _biggerFont, ), ); }, ); final List<Widget> divided = ListTile.divideTiles( context: context, tiles: tiles, ).toList(); return new Scaffold( appBar: new AppBar( title: const Text('收藏列表'), ), body: new ListView(children: divided), ); }, ), ); } }
将包依赖项添加到应用程序
最终效果:
参考
https://flutter.cn/docs/get-started/codelab
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。