昨天已经把flutter的开发环境搭建完成,从今天起就开始试着编写一些简单的页面,在开发的过程中,主要使用的Dart语法。想要了解Dart的可以点击下面的官网链接去了解。
官网链接
学习一门语言,从学会Hello World开始,下面开始say Hello。
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { String title='Flutter 第一天'; return MaterialApp( title: title, theme: ThemeData( primarySwatch: Colors.blue, ), home: new Scaffold( appBar: new AppBar(title: new Text(title)), body: new Center( child: new Text('Hello World',), ), ) ); } }
最终实现效果如下图:
english_words: ^4.0.0
1、一个StatefulWidget类
2、一个State类
import 'package:flutter/material.dart'; import 'package:english_words/english_words.dart'; class RandomWordsState extends State<RandomWords> { final _suggestions = <WordPair>[]; final _biggerFont = const TextStyle(fontSize: 18.0); //添加收藏 final _saved = new Set<WordPair>(); @override Widget build(BuildContext context) { /*final wordPair = new WordPair.random(); return new Text(wordPair.asPascalCase);*/ void _pushSaved(){ Navigator.of(context).push( new MaterialPageRoute( builder: (context) { final tiles = _saved.map( (pair) { return new ListTile( title: new Text( pair.asPascalCase, style: _biggerFont, ), ); }, ); final divided = ListTile .divideTiles( context: context, tiles: tiles, ).toList(); return new Scaffold( appBar: new AppBar( title: new Text("Savad Suggestions"), ), body: new ListView(children: divided,), ); }, ),); } return new Scaffold( appBar: new AppBar( title: new Text('Startup Name Generator'), actions: <Widget>[ new IconButton(icon: new Icon(Icons.list),onPressed: _pushSaved ) ], ), body: _buildSuggestions(), ); } ///用来构建一行的Widget,行的内容为一个随机生成的单词对和一个图标 Widget _buildRow(WordPair pair){ final alreadySaved = _saved.contains(pair); return new ListTile( title: new 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); } }); }, ); } Widget _buildSuggestions() { return new ListView.builder( padding: const EdgeInsets.all(16.0), itemBuilder: (context,i) { if(i.isOdd) return new Divider(); final index = i ~/2; if(index >= _suggestions.length){ _suggestions.addAll(generateWordPairs().take(10)); } return _buildRow(_suggestions[index]); } ); } } class RandomWords extends StatefulWidget { @override RandomWordsState createState() => new RandomWordsState(); }
import 'package:flutter/material.dart'; import 'package:wangbl_flutter/random_words.dart'; class Day2App extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { String title='Flutter 第二天'; return MaterialApp( title: title, theme: ThemeData( primarySwatch: Colors.blue, ), home: new RandomWords() ); } }
如果运行过程中出现问题的话,可以参考我github上的代码,或者直接将我的代码down下来运行。
传送门
好了,第二天内容到此结束,感谢阅读。