flutter 中的小部件的使用
查看 Flutter 官方文档,给自己加深印象
flutter 小部件简介
flutter 中的小部件不同于Android中的View ,小部件具有不同生命周期!!!(在Android中,view生命周期是直到结束)它们也是不可变了。因为每次改变,都是创建新的小部件实例。相比之下,Android都是通过setXXX 去改变旧的属性。
它是极其轻巧的。因为它只负责描述,而不是去绘制实际视图
flutter 小部件的使用
通过查看部分文档,发现它的使用与 Vue 有点相似???
可变的小部件和不可变小部件
可变的小部件指的是,可以改变小部件中的文字等信息。不可变指的是不需要改变文字,布尔值等信息的小部件。例如 Activity 的Title 就不需要改变
在 Flutter
中,使用 StatelessWidget
来描述不可变窗口,使用 StatefulWidget 描述可变窗口,例如:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final wordPair = WordPair.random();
return MaterialApp(
title: 'this is my first flutter app',
home: RandomWords(),
theme: ThemeData(
primaryColor: Colors.white,
),
);
}
}
这个小部件中,
title
是不可变的
class RandomWords extends StatefulWidget {
@override
RandomWordsState createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
// add icon and list
final _saved = new Set<WordPair>();
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
@override
Widget build(BuildContext context) {
final wordPair = WordPair.random();
// return Text(wordPair.asPascalCase);
return Scaffold(
appBar: AppBar(
title: Text('startup name generator'),
),
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: new Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: () {
setState(() {
if (alreadySaved) {
_saved.remove(pair);
} else {
_saved.add(pair);
}
});
},
);
}
}
在这个小部件中,列表选中状态就是可变的,通过
onTap
点击事件,调用setState
往 list 中 移除或者添加 pair ,这样,就会引起界面的重绘
小部件的添加和删除
在 flutter 中,不能和Android 一样,在代码中使用 removeChild 或者 addChild ,它只能在 State 小部件中,通过setState 方法,然后通过判断,来动态的创建或移除小部件
import 'package:flutter/material.dart';
void main() => runApp(SampleApp());
class SampleApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sample App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
SampleAppPage({Key key}) : super(key: key);
@override
_SampleAppPageState createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
// Default value for toggle
bool toggle = true;
void _toggle() {
setState(() {
toggle = !toggle;
});
}
_getToggleChild() {
if (toggle) {
return Text('Toggle One');
} else {
return MaterialButton(onPressed: () {}, child: Text('Toggle Two'));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sample App"),
),
body: Center(
child: _getToggleChild(),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggle,
tooltip: 'Update Text',
child: Icon(Icons.update),
),
);
}
}
给我的感觉是更像 Vue 了......
flutter 中如何使用窗口动画
在Android中,窗口动画一般自定义 xml 文件,然后在布局文件中引用,或者代码使用 alpha 定义颜色,使用 state
切换。
在 Flutter 中,使用控制器 AnimationController
控制动画的执行,可以交由其他 小部件进行动画的计算。如:CurvedAnimation
import 'package:flutter/material.dart';
void main() {
runApp(FadeAppTest());
}
class FadeAppTest extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fade Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyFadeTest(title: 'Fade Demo'),
);
}
}
class MyFadeTest extends StatefulWidget {
MyFadeTest({Key key, this.title}) : super(key: key);
final String title;
@override
_MyFadeTest createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
AnimationController controller;
CurvedAnimation curve;
@override
void initState() {
controller = AnimationController(duration: const Duration(milliseconds: 2000), vsync: this);
curve = CurvedAnimation(parent: controller, curve: Curves.easeIn);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Container(
child: FadeTransition(
opacity: curve,
child: FlutterLogo(
size: 100.0,
)))),
floatingActionButton: FloatingActionButton(
tooltip: 'Fade',
child: Icon(Icons.brush),
onPressed: () {
controller.forward();
},
),
);
}
}
Flutter 中使用画布
在Android中,需要自定义文字显示,或者其它图像的时候,需要自定义 Canvas ,使用draw 绘制,在Flutter中,提供了最简单的画图示例:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: DemoApp()));
class DemoApp extends StatelessWidget {
Widget build(BuildContext context) => Scaffold(body: Signature());
}
class Signature extends StatefulWidget {
SignatureState createState() => SignatureState();
}
class SignatureState extends State<Signature> {
List<Offset> _points = <Offset>[];
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (DragUpdateDetails details) {
setState(() {
RenderBox referenceBox = context.findRenderObject();
Offset localPosition =
referenceBox.globalToLocal(details.globalPosition);
_points = List.from(_points)..add(localPosition);
});
},
onPanEnd: (DragEndDetails details) => _points.add(null),
child: CustomPaint(painter: SignaturePainter(_points), size: Size.infinite),
);
}
}
class SignaturePainter extends CustomPainter {
SignaturePainter(this.points);
final List<Offset> points;
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null)
canvas.drawLine(points[i], points[i + 1], paint);
}
}
bool shouldRepaint(SignaturePainter other) => other.points != points;
}
返回一个 GestureDetector
小部件,在 onPanUpdate
中记录每次途径的路径,使用 setState
更新界面。
如何自定义View
在Android中,如果需要自定义控件,可以定义子类,然后覆写父类的方法,例如,如果要在
ImageView
的图片上覆盖蒙版,可以自定义类,然后覆写setImageBitmap
方法,在bitmap
上添加蒙版。但是在flutter中,推荐使用各种小部件的方式组合成一个真正需要的小部件
如果需要自定义一个按钮,则可以编写CustomButtom
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: DemoApp()));
class DemoApp extends StatelessWidget {
// Widget build(BuildContext context) => Scaffold(body: Signature());
Widget build(BuildContext context){
return Center(
child:CustomButton("buttom")
);
}
}
class CustomButton extends StatelessWidget {
final String label;
CustomButton(this.label);
@override
Widget build(BuildContext context) {
return RaisedButton(onPressed: () {}, child: Text(label));
}
}
然后使RaisedButtom
成为其子类