一、前言
本系列文章旨在快速复习并上手Flutter开发,并在适当分享在项目实战过程中遇到的一些比较有价值的知识内容:
- 一、了解Flutter开发
-
- Flutter的特性与应用场景
-
- Flutter绘制原理
-
- 与Flutter相关的技术原理
-
- 搭建Flutter开发环境
-
- 创建Flutter项目的几种方式
-
- 二、快速入门Flutter开发知识大纲
-
- Dart语言快速入门
-
- Flutter的Widget
-
- 三、常见应用功能模块与开源项目
-
- 常见应用功能模块
-
- 不错的开源项目
-
二、 StatefulWidget
StatelessWidget与StatefulWidget的区别
- 在开发中,某些Widget情况下我们展示的数据并不是一成不变的:
- 比如Flutter默认程序中的计数器案例,点击了+号按钮后,显示的数字需要+1;
- 比如在开发中,我们会进行下拉刷新、上拉加载更多,这时数据也会发生变化;
StatelessWidget
通常用来展示哪些数据固定不变的- 如果数据会发生改变,我们使用
StatefulWidget
;
1. 认识StatefulWidget
1.1 StatefulWidget介绍
如果你有阅读过我们创建Flutter工程时候的默认程序,那么你会发现它创建的是一个 StatefulWidget
。
- 默认程序
import 'package:flutter/material.dart';void main() {runApp(const MyApp());}class MyApp extends StatelessWidget {const MyApp({super.key});// This widget is the root of your application.@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(// This is the theme of your application.//// TRY THIS: Try running your application with "flutter run". You'll see// the application has a blue toolbar. Then, without quitting the app,// try changing the seedColor in the colorScheme below to Colors.green// and then invoke "hot reload" (save your changes or press the "hot// reload" button in a Flutter-supported IDE, or press "r" if you used// the command line to start the app).//// Notice that the counter didn't reset back to zero; the application// state is not lost during the reload. To reset the state, use hot// restart instead.//// This works for code too, not just values: Most code changes can be// tested with just a hot reload.colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),useMaterial3: true,),home: const MyHomePage(title: 'Flutter Demo Home Page'),);}}class MyHomePage extends StatefulWidget {const MyHomePage({super.key, required this.title});// This widget is the home page of your application. It is stateful, meaning// that it has a State object (defined below) that contains fields that affect// how it looks.// This class is the configuration for the state. It holds the values (in this// case the title) provided by the parent (in this case the App widget) and// used by the build method of the State. Fields in a Widget subclass are// always marked "final".final String title;@overrideState<MyHomePage> createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {int _counter = 0;void _incrementCounter() {setState(() {// This call to setState tells the Flutter framework that something has// changed in this State, which causes it to rerun the build method below// so that the display can reflect the updated values. If we changed// _counter without calling setState(), then the build method would not be// called again, and so nothing would appear to happen._counter++;});}@overrideWidget build(BuildContext context) {// This method is rerun every time setState is called, for instance as done// by the _incrementCounter method above.//// The Flutter framework has been optimized to make rerunning build methods// fast, so that you can just rebuild anything that needs updating rather// than having to individually change instances of widgets.return Scaffold(appBar: AppBar(// TRY THIS: Try changing the color here to a specific color (to// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar// change color while the other colors stay the same.backgroundColor: Theme.of(context).colorScheme.inversePrimary,// Here we take the value from the MyHomePage object that was created by// the App.build method, and use it to set our appbar title.title: Text(widget.title),),body: Center(// Center is a layout widget. It takes a single child and positions it// in the middle of the parent.child: Column(// Column is also a layout widget. It takes a list of children and// arranges them vertically. By default, it sizes itself to fit its// children horizontally, and tries to be as tall as its parent.//// Column has various properties to control how it sizes itself and// how it positions its children. Here we use mainAxisAlignment to// center the children vertically; the main axis here is the vertical// axis because Columns are vertical (the cross axis would be// horizontal).//// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"// action in the IDE, or press "p" in the console), to see the// wireframe for each widget.mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[const Text('You have pushed the button this many times:',),Text('$_counter',style: Theme.of(context).textTheme.headlineMedium,),],),),floatingActionButton: FloatingActionButton(onPressed: _incrementCounter,tooltip: 'Increment',child: const Icon(Icons.add),), // This trailing comma makes auto-formatting nicer for build methods.);}}
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // TRY THIS: Try running your application with "flutter run". You'll see // the application has a blue toolbar. Then, without quitting the app, // try changing the seedColor in the colorScheme below to Colors.green // and then invoke "hot reload" (save your changes or press the "hot // reload" button in a Flutter-supported IDE, or press "r" if you used // the command line to start the app). // // Notice that the counter didn't reset back to zero; the application // state is not lost during the reload. To reset the state, use hot // restart instead. // // This works for code too, not just values: Most code changes can be // tested with just a hot reload. colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // TRY THIS: Try changing the color here to a specific color (to // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar // change color while the other colors stay the same. backgroundColor: Theme.of(context).colorScheme.inversePrimary, // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). // // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" // action in the IDE, or press "p" in the console), to see the // wireframe for each widget. mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // TRY THIS: Try running your application with "flutter run". You'll see // the application has a blue toolbar. Then, without quitting the app, // try changing the seedColor in the colorScheme below to Colors.green // and then invoke "hot reload" (save your changes or press the "hot // reload" button in a Flutter-supported IDE, or press "r" if you used // the command line to start the app). // // Notice that the counter didn't reset back to zero; the application // state is not lost during the reload. To reset the state, use hot // restart instead. // // This works for code too, not just values: Most code changes can be // tested with just a hot reload. colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // TRY THIS: Try changing the color here to a specific color (to // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar // change color while the other colors stay the same. backgroundColor: Theme.of(context).colorScheme.inversePrimary, // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). // // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" // action in the IDE, or press "p" in the console), to see the // wireframe for each widget. mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
为什么选择StatefulWidget
呢?
- 因为在示例代码中,当我们点击按钮时,界面上显示的数据会发生改变;
- 这时,我们需要一个
变量
来记录当前的状态,再把这个变量显示到某个Text Widget
上; - 并且每次
变量
发生改变时,我们对应的Text上显示的内容也要发生改变;
但是有一个问题,我之前说过定义到 Widget
中的数据都是不可变的,必须定义为 final
,为什么呢?
- 这次因为
Flutter
在设计的时候就决定了一旦Widget
中展示的数据发生变化,就重新构建整个Widget
; - 我们在关注
Flutter
的渲染原理的时候会进一步介绍:Flutter
通过一些机制来限定定义到Widget
中的成员变量
必须是final
的;
Flutter如何做到我们在开发中定义到Widget中的数据一定是final的呢?
我们来看一下Widget的源码:
@immutableabstract class Widget extends DiagnosticableTree {// ...省略代码}@immutable abstract class Widget extends DiagnosticableTree { // ...省略代码 }@immutable abstract class Widget extends DiagnosticableTree { // ...省略代码 }
这里有一个很关键的东西@immutable
- 我们似乎在
Dart
中没有见过这种语法,这实际上是一个注解
,这设计到Dart的元编程,我们这里不展开讲; - 我们在这里一起探索一下这个@immutable是干什么的;
实际上官方有对@immutable进行说明:
- 来源: api.flutter.dev/flutter/met…
- 说明: 被
@immutable
注解标明的类或者子类都必须是不可变的
- 结论: 定义到Widget中的数据一定是不可变的,需要使用final来修饰
1.2 如何存储Widget状态?
既然 Widget
是不可变,那么 StatefulWidget
如何来存储可变的状态呢?
StatelessWidget
无所谓,因为它里面的数据通常是直接定义完后就不修改的。- 但
StatefulWidget
需要有状态(可以理解成变量)的改变,这如何做到呢?
Flutter
将 StatefulWidget
设计成了两个类:
- 也就是你创建
StatefulWidget
时必须创建两个类: - 一个类继承自
StatefulWidget
,作为Widget树的一部分; - 一个类继承自
State
,用于记录StatefulWidget
会变化的状态,并且根据状态的变化,构建出新的Widget;
创建一个StatefulWidget
,我们通常会按照如下格式来做:
- 当Flutter在构建Widget Tree时,会获取
State的实例
,并且它调用build方法去获取StatefulWidget希望构建的Widget; - 那么,我们就可以将需要保存的状态保存在MyState中,因为它是可变的;
class MyStatefulWidget extends StatefulWidget {@overrideState<StatefulWidget> createState() {// 将创建的State返回return MyState();}}class MyState extends State<MyStatefulWidget> {@overrideWidget build(BuildContext context) {return <构建自己的Widget>;}}class MyStatefulWidget extends StatefulWidget { @override State<StatefulWidget> createState() { // 将创建的State返回 return MyState(); } } class MyState extends State<MyStatefulWidget> { @override Widget build(BuildContext context) { return <构建自己的Widget>; } }class MyStatefulWidget extends StatefulWidget { @override State<StatefulWidget> createState() { // 将创建的State返回 return MyState(); } } class MyState extends State<MyStatefulWidget> { @override Widget build(BuildContext context) { return <构建自己的Widget>; } }
思考:为什么Flutter要这样设计呢?
这是因为在Flutter中,只要数据改变了Widget就需要重新构建(rebuild)
2. StatefulWidget案例
2.1 案例效果和分析
我们通过一个计数器案例来练习一下StatefulWidget
:
案例效果以及布局如下:
Column
小部件:之前我们已经用过,当有垂直方向布局时,我们就使用它;Row
小部件:之前也用过,当时水平方向布局时,我们就使用它;MaterialButton
小部件:可以创建一个按钮,并且其中有一个onPress属性
是传入一个回调函数
,当按钮点击时被回调;
2.2 创建StatefulWidget
下面我们来看看代码实现:
- 因为当点击按钮时,数字会发生变化,所以我们需要使用一个StatefulWidget,所以我们需要创建两个类;
HomePageCounterWidget
继承自StatefulWidget
,里面需要实现createState
方法;HomePageCounterWidgetState
继承自State
,里面实现build
方法,并且可以定义一些成员变量;
class HomePageCounterWidget extends StatefulWidget {@overrideState<StatefulWidget> createState() {// 返回一个Statereturn HomePageCounterWidgetState();}}class HomePageCounterWidgetState extends State<HomePageCounterWidget> {int counter = 0;final style = TextStyle(fontSize: 18, color: Colors.white);@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Text("当前计数:$counter", style: TextStyle(fontSize: 25)),],),);}}class HomePageCounterWidget extends StatefulWidget { @override State<StatefulWidget> createState() { // 返回一个State return HomePageCounterWidgetState(); } } class HomePageCounterWidgetState extends State<HomePageCounterWidget> { int counter = 0; final style = TextStyle(fontSize: 18, color: Colors.white); @override Widget build(BuildContext context) { // TODO: implement build return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text("当前计数:$counter", style: TextStyle(fontSize: 25)), ], ), ); } }class HomePageCounterWidget extends StatefulWidget { @override State<StatefulWidget> createState() { // 返回一个State return HomePageCounterWidgetState(); } } class HomePageCounterWidgetState extends State<HomePageCounterWidget> { int counter = 0; final style = TextStyle(fontSize: 18, color: Colors.white); @override Widget build(BuildContext context) { // TODO: implement build return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text("当前计数:$counter", style: TextStyle(fontSize: 25)), ], ), ); } }
2.3 实现按钮的布局
class HomePageCounterWidget extends StatefulWidget {@overrideState<StatefulWidget> createState() {return HomePageCounterWidgetState();}}class HomePageCounterWidgetState extends State<HomePageCounterWidget> {int counter = 0;final style = TextStyle(fontSize: 18, color: Colors.white);@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Row(//横向mainAxisAlignment: MainAxisAlignment.center,//局中children: <Widget>[MaterialButton(color: Colors.redAccent,child: Text("+1", style: style),onPressed: () {//按钮的回调处理}),MaterialButton(color: Colors.greenAccent,child: Text("-1", style: style),onPressed: () {}),],),Text("当前计数:$counter", style: TextStyle(fontSize: 25)),],),);}}class HomePageCounterWidget extends StatefulWidget { @override State<StatefulWidget> createState() { return HomePageCounterWidgetState(); } } class HomePageCounterWidgetState extends State<HomePageCounterWidget> { int counter = 0; final style = TextStyle(fontSize: 18, color: Colors.white); @override Widget build(BuildContext context) { // TODO: implement build return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row(//横向 mainAxisAlignment: MainAxisAlignment.center,//局中 children: <Widget>[ MaterialButton(color: Colors.redAccent, child: Text("+1", style: style), onPressed: () {//按钮的回调处理 }), MaterialButton(color: Colors.greenAccent, child: Text("-1", style: style), onPressed: () { }), ], ), Text("当前计数:$counter", style: TextStyle(fontSize: 25)), ], ), ); } }class HomePageCounterWidget extends StatefulWidget { @override State<StatefulWidget> createState() { return HomePageCounterWidgetState(); } } class HomePageCounterWidgetState extends State<HomePageCounterWidget> { int counter = 0; final style = TextStyle(fontSize: 18, color: Colors.white); @override Widget build(BuildContext context) { // TODO: implement build return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row(//横向 mainAxisAlignment: MainAxisAlignment.center,//局中 children: <Widget>[ MaterialButton(color: Colors.redAccent, child: Text("+1", style: style), onPressed: () {//按钮的回调处理 }), MaterialButton(color: Colors.greenAccent, child: Text("-1", style: style), onPressed: () { }), ], ), Text("当前计数:$counter", style: TextStyle(fontSize: 25)), ], ), ); } }
2.4 按钮点击状态改变
我们现在要监听状态的改变,当状态改变时要修改counter变量
- 但是,直接修改变量可以改变界面吗?不可以。
- 这是因为Flutter并不知道我们的数据发生了改变,需要来重新构建我们界面中的Widget;
如何可以让Flutter知道我们的状态发生改变了,重新构建我们的Widget呢?
- 在Flutter中,通常将
setState
函数用于更新组件的状态。setState
函数是StatefulWidget
类中的一个方法,用于通知 Flutter 框架组件的状态发生了改变,从而触发界面的重建。
- 当组件的状态发生变化时,我们需要调用
setState
方法,并在其中更新相关的状态变量。 - 一旦调用了
setState
,Flutter 就会重建当前组件,以显示新的状态。 - 这样,界面就会根据最新的状态重新绘制,实现了状态和界面的同步更新
onPressed: () {setState(() {counter++;});},onPressed: () { setState(() { counter++; }); },onPressed: () { setState(() { counter++; }); },
这样就可以实现想要的效果了:
3. StatefulWidget生命周期
3.1 生命周期的理解
什么是生命周期呢?
- 客户端开发:
iOS开发
中我们需要知道UIViewController
从创建到销毁的整个过程;Android开发
中我们需要知道Activity
从创建到销毁的整个过程。以便在不同的生命周期方法中完成不同的操作;
- 前端开发中:
Vue
、React
开发中组件也都有自己的生命周期,在不同的生命周期中我们可以做不同的操作;
Flutter Widget
的生命周期:
StatelessWidget
可以由父Widget
直接传入值,调用build
方法来构建,整个过程非常简单;- 而
StatefulWidget
需要通过State
来管理其数据,并且还要监控状态的改变决定是否重新build
整个Widget; - 所以,我们 主要讨论
StatefulWidget
的生命周期 ,也就是它从创建到销毁的整个过程;
3.2 生命周期的简单版
在这个版本中,我讲解那些常用的方法和回调,下一个版本中我解释一些比较复杂的方法和回调
那么 StatefulWidget
有哪些生命周期的回调呢?它们分别在什么情况下执行呢?
- 在下图中,灰色部分的内容是Flutter内部操作的,我们并不需要手动去设置它们;
- 白色部分表示我们可以去监听到或者可以手动调用的方法;
我们知道StatefulWidget本身由两个类组成的:StatefulWidget
和State
,我们分开进行分析
首先,执行 StatefulWidget
中相关的方法:
- 1、执行
StatefulWidget
的构造函数(Constructor)来创建出StatefulWidget; - 2、执行
StatefulWidget
的createState方法,来创建一个维护StatefulWidget的State对象;
其次,调用createState
创建State对象时,执行State类的相关方法:
- 1、执行
State
类的构造方法(Constructor)来创建State对象; - 2、执行
initState
,我们通常会在这个方法中执行一些数据初始化的操作,或者也可能会发送网络请求;- 注意:这个方法是重写父类的方法,必须调用super,因为父类中会进行一些其他操作;
- 并且如果你阅读源码,你会发现这里有一个注解(annotation):
@mustCallSuper
- 3、执行
didChangeDependencies
方法,这个方法在两种情况下会调用- 情况一:调用initState会调用;
- 情况二:从其他对象中依赖一些数据发生改变时,比如前面我们提到的InheritedWidget(这个后面会讲到);
- 4、
Flutter
执行build
方法,来看一下我们当前的Widget
需要渲染哪些Widget
; - 5、当前的
Widget
不再使用时,会调用dispose
进行销毁; - 6、手动调用
setState
方法,会根据最新的状态(数据)来重新调用build
方法,构建对应的Widgets; - 7、执行
didUpdateWidget
方法是在当父Widget
触发重建(rebuild
)时,系统会调用didUpdateWidget
方法;
我们来通过代码进行演示:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {@overrideWidget build(BuildContext context) {print("HomePageBody-build");return HomePageCounterWidget();}}class HomePageCounterWidget extends StatefulWidget {HomePageCounterWidget(){print("HomePageCounterWidget()");}@overrideState<StatefulWidget> createState() {print("HomePageCounterWidget-createState");return HomePageCounterWidgetState();}}class HomePageCounterWidgetState extends State<HomePageCounterWidget> {int counter = 0;final style = TextStyle(fontSize: 18, color: Colors.white);HomePageCounterWidgetState(){print("HomePageCounterWidgetState()");}@overridevoid initState() {super.initState();print("HomePageCounterWidgetState-initState");}@overridevoid didChangeDependencies() {super.didChangeDependencies();print("HomePageCounterWidgetState-didChangeDependencies");}@overrideWidget build(BuildContext context) {print("HomePageCounterWidgetState-build");return Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Row(//横向mainAxisAlignment: MainAxisAlignment.center,//局中children: <Widget>[MaterialButton(color: Colors.redAccent,child: Text("+1", style: style),onPressed: () {//按钮的回调处理this.setState(() => counter += 1);}),MaterialButton(color: Colors.greenAccent,child: Text("-1", style: style),onPressed: () {setState(() {if (counter > 0) {counter -= 1;}});}),],),Text("当前计数:$counter", style: TextStyle(fontSize: 25)),],),);}@overridevoid didUpdateWidget(covariant HomePageCounterWidget oldWidget) {super.didUpdateWidget(oldWidget);print("HomePageCounterWidgetState-didUpdateWidget");}@overridevoid dispose() {super.dispose();print("HomePageCounterWidgetState-dispose");}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { print("HomePageBody-build"); return HomePageCounterWidget(); } } class HomePageCounterWidget extends StatefulWidget { HomePageCounterWidget(){ print("HomePageCounterWidget()"); } @override State<StatefulWidget> createState() { print("HomePageCounterWidget-createState"); return HomePageCounterWidgetState(); } } class HomePageCounterWidgetState extends State<HomePageCounterWidget> { int counter = 0; final style = TextStyle(fontSize: 18, color: Colors.white); HomePageCounterWidgetState(){ print("HomePageCounterWidgetState()"); } @override void initState() { super.initState(); print("HomePageCounterWidgetState-initState"); } @override void didChangeDependencies() { super.didChangeDependencies(); print("HomePageCounterWidgetState-didChangeDependencies"); } @override Widget build(BuildContext context) { print("HomePageCounterWidgetState-build"); return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row(//横向 mainAxisAlignment: MainAxisAlignment.center,//局中 children: <Widget>[ MaterialButton(color: Colors.redAccent, child: Text("+1", style: style), onPressed: () {//按钮的回调处理 this.setState(() => counter += 1); }), MaterialButton(color: Colors.greenAccent, child: Text("-1", style: style), onPressed: () { setState(() { if (counter > 0) { counter -= 1; } }); }), ], ), Text("当前计数:$counter", style: TextStyle(fontSize: 25)), ], ), ); } @override void didUpdateWidget(covariant HomePageCounterWidget oldWidget) { super.didUpdateWidget(oldWidget); print("HomePageCounterWidgetState-didUpdateWidget"); } @override void dispose() { super.dispose(); print("HomePageCounterWidgetState-dispose"); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { print("HomePageBody-build"); return HomePageCounterWidget(); } } class HomePageCounterWidget extends StatefulWidget { HomePageCounterWidget(){ print("HomePageCounterWidget()"); } @override State<StatefulWidget> createState() { print("HomePageCounterWidget-createState"); return HomePageCounterWidgetState(); } } class HomePageCounterWidgetState extends State<HomePageCounterWidget> { int counter = 0; final style = TextStyle(fontSize: 18, color: Colors.white); HomePageCounterWidgetState(){ print("HomePageCounterWidgetState()"); } @override void initState() { super.initState(); print("HomePageCounterWidgetState-initState"); } @override void didChangeDependencies() { super.didChangeDependencies(); print("HomePageCounterWidgetState-didChangeDependencies"); } @override Widget build(BuildContext context) { print("HomePageCounterWidgetState-build"); return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row(//横向 mainAxisAlignment: MainAxisAlignment.center,//局中 children: <Widget>[ MaterialButton(color: Colors.redAccent, child: Text("+1", style: style), onPressed: () {//按钮的回调处理 this.setState(() => counter += 1); }), MaterialButton(color: Colors.greenAccent, child: Text("-1", style: style), onPressed: () { setState(() { if (counter > 0) { counter -= 1; } }); }), ], ), Text("当前计数:$counter", style: TextStyle(fontSize: 25)), ], ), ); } @override void didUpdateWidget(covariant HomePageCounterWidget oldWidget) { super.didUpdateWidget(oldWidget); print("HomePageCounterWidgetState-didUpdateWidget"); } @override void dispose() { super.dispose(); print("HomePageCounterWidgetState-dispose"); } }
打印结果如下:
flutter: HomePageBody-buildflutter: HomePageCounterWidget()flutter: HomePageCounterWidget-createStateflutter: HomePageCounterWidgetState()flutter: HomePageCounterWidgetState-initStateflutter: HomePageCounterWidgetState-didChangeDependenciesflutter: HomePageCounterWidgetState-buildflutter: HomePageBody-build flutter: HomePageCounterWidget() flutter: HomePageCounterWidget-createState flutter: HomePageCounterWidgetState() flutter: HomePageCounterWidgetState-initState flutter: HomePageCounterWidgetState-didChangeDependencies flutter: HomePageCounterWidgetState-buildflutter: HomePageBody-build flutter: HomePageCounterWidget() flutter: HomePageCounterWidget-createState flutter: HomePageCounterWidgetState() flutter: HomePageCounterWidgetState-initState flutter: HomePageCounterWidgetState-didChangeDependencies flutter: HomePageCounterWidgetState-build
当我们改变状态,手动执行setState方法后会打印如下结果:
flutter: HomePageCounterWidgetState-buildflutter: HomePageCounterWidgetState-buildflutter: HomePageCounterWidgetState-build
3.3 生命周期的复杂版(选读)
我们来学习几个前面生命周期图中提到的属性,但是没有详细讲解的
1、mounted
是State
内部设置的一个属性,事实上我们不了解它也可以,但是如果你想深入了解它,会对State的机制理解更加清晰;
- 很多资料没有提到这个属性,但是我这里把它列出来,是内部设置的,不需要我们手动进行修改;
2、dirty state
的含义是脏的State
- 它实际是通过一个Element的东西(我们还没有讲到Flutter绘制原理)的属性来标记的;
- 将它标记为dirty会等待下一次的重绘检查,强制调用build方法来构建我们的Widget;
-(有机会我专门写一篇关于StatelessWidget和StatefulWidget的区别,讲解一些它们开发中的选择问题);
3、clean state
的含义是干净的State
- 它表示当前build出来的Widget,下一次重绘检查时不需要重新build;
三. Flutter的编程范式
这个章节又讲解一些理论的东西,可能并不会直接讲授Flutter的知识,但是会对你以后写任何的代码,都具备一些简单的知道思想;
1. 编程范式的理解
编程范式对于初学编程的人来说是一个虚无缥缈的东西,但是却是我们日常开发中都在默认遵循的一些模式和方法;
比如我们最为熟悉的 面向对象编程
就是一种编程范式,与之对应或者结合开发的包括:面向过程编程、函数式编程、面向协议编程;
另外还有两个对应的编程范式:命令式编程
和 声明式编程
- 命令式编程: 命令式编程非常好理解,就是一步步给计算机命令,告诉它我们想做什么事情;
- 声明式编程: 声明式编程通常是描述目标的性质,你应该是什么样的,依赖哪些状态,并且当依赖的状态发生改变时,我们通过某些方式通知目标作出相应;
上面的描述还是太笼统了,我们来看一些具体点的例子;
2. Flutter的编程范式
从2009年开始(数据来自维基百科),声明式编程就开始流行起来,并且目前在Vue
、React
、包括iOS中的SwiftUI
中以及Flutter
目前都采用了声明式编程。
现在我们来开发一个需求:显示一个Hello World,之后又修改成了Hello Flutter
如果是传统的命令式编程,我们开发Flutter的模式很可能是这样的:(注意是想象中的伪代码)
- 整个过程,我们需要一步步告诉Flutter它需要做什么;
final text = new Text();var title = "Hello World";text.setContent(title);// 修改数据title = "Hello Flutter";text.setContent(title);final text = new Text(); var title = "Hello World"; text.setContent(title); // 修改数据 title = "Hello Flutter"; text.setContent(title);final text = new Text(); var title = "Hello World"; text.setContent(title); // 修改数据 title = "Hello Flutter"; text.setContent(title);
如果是声明式编程,我们通常会维护一套数据集:
- 这个数据集可能来自己父类、来自自身State管理、来自InheritedWidget、来自统一的状态管理的地方;
- 总之,我们知道有这么一个数据集,并且告诉Flutter这些数据集在哪里使用;
var title = "Hello World";Text(title); // 告诉Text内部显示的是title// 数据改变title = "Hello Flutter";setState(() => null); // 通知重新build Widget即可var title = "Hello World"; Text(title); // 告诉Text内部显示的是title // 数据改变 title = "Hello Flutter"; setState(() => null); // 通知重新build Widget即可var title = "Hello World"; Text(title); // 告诉Text内部显示的是title // 数据改变 title = "Hello Flutter"; setState(() => null); // 通知重新build Widget即可
四、文本Widget
- 在Android中,我们使用
TextView
- iOS中我们使用
UILabel
来显示文本; - Flutter中,我们使用
Text组件
控制文本如何展示;
1. 普通文本展示
在Flutter中,我们可以将文本的控制显示分成两类:
- 控制文本布局的参数: 如文本对齐方式 textAlign、文本排版方向 textDirection,文本显示最大行数 maxLines、文本截断规则 overflow 等等,这些都是构造函数中的参数;
- 控制文本样式的参数: 如字体名称 fontFamily、字体大小 fontSize、文本颜色 color、文本阴影 shadows 等等,这些参数被统一封装到了构造函数中的参数 style 中;
下面我们来看一下其中一些属性的使用:
class MyHomeBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Text("《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。",style: TextStyle(fontSize: 20,color: Colors.purple),);}}class MyHomeBody extends StatelessWidget { @override Widget build(BuildContext context) { return Text( "《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。", style: TextStyle( fontSize: 20, color: Colors.purple ), ); } }class MyHomeBody extends StatelessWidget { @override Widget build(BuildContext context) { return Text( "《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。", style: TextStyle( fontSize: 20, color: Colors.purple ), ); } }
展示效果如下:
我们可以通过一些属性来改变Text的布局:
textAlign
:文本对齐方式,比如TextAlign.centermaxLines
:最大显示行数,比如1overflow
:超出部分显示方式,比如TextOverflow.ellipsistextScaleFactor
:控制文本缩放,比如1.24
代码如下:
class MyHomeBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Text("《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。",textAlign: TextAlign.center, // 所有内容都居中对齐maxLines: 3, // 显然 "生。" 被删除了overflow: TextOverflow.ellipsis, // 超出部分显示...// textScaleFactor: 1.25,style: TextStyle(fontSize: 20,color: Colors.purple),);}}class MyHomeBody extends StatelessWidget { @override Widget build(BuildContext context) { return Text( "《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。", textAlign: TextAlign.center, // 所有内容都居中对齐 maxLines: 3, // 显然 "生。" 被删除了 overflow: TextOverflow.ellipsis, // 超出部分显示... // textScaleFactor: 1.25, style: TextStyle( fontSize: 20, color: Colors.purple ), ); } }class MyHomeBody extends StatelessWidget { @override Widget build(BuildContext context) { return Text( "《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。", textAlign: TextAlign.center, // 所有内容都居中对齐 maxLines: 3, // 显然 "生。" 被删除了 overflow: TextOverflow.ellipsis, // 超出部分显示... // textScaleFactor: 1.25, style: TextStyle( fontSize: 20, color: Colors.purple ), ); } }
2. 富文本展示
前面展示的文本,我们都应用了相同的样式,如果我们希望给他们不同的样式呢?
- 比如《定风波》我希望字体更大一点,并且是黑色字体,并且有加粗效果;
- 比如 苏轼 我希望是红色字体;
如果希望展示这种混合样式,那么我们可以利用分片来进行操作
- 在Android中,我们可以使用SpannableString
- 在iOS中,我们可以使用NSAttributedString完成
代码如下:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {final titleStyle = TextStyle(fontSize: 25, fontWeight: FontWeight.bold, color: Colors.black);final nameStyle = TextStyle(fontSize: 18, color: Colors.redAccent);final contentStyle = TextStyle(fontSize: 20, color: Colors.purple);@overrideWidget build(BuildContext context) {return Text.rich(TextSpan(children: [TextSpan(text: "《定风波》", style: titleStyle),TextSpan(text: "苏轼", style: nameStyle),TextSpan(text: "\n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。")]),style:contentStyle ,textAlign: TextAlign.center,);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { final titleStyle = TextStyle(fontSize: 25, fontWeight: FontWeight.bold, color: Colors.black); final nameStyle = TextStyle(fontSize: 18, color: Colors.redAccent); final contentStyle = TextStyle(fontSize: 20, color: Colors.purple); @override Widget build(BuildContext context) { return Text.rich( TextSpan( children: [ TextSpan(text: "《定风波》", style: titleStyle), TextSpan(text: "苏轼", style: nameStyle), TextSpan(text: "\n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。") ] ), style:contentStyle , textAlign: TextAlign.center, ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { final titleStyle = TextStyle(fontSize: 25, fontWeight: FontWeight.bold, color: Colors.black); final nameStyle = TextStyle(fontSize: 18, color: Colors.redAccent); final contentStyle = TextStyle(fontSize: 20, color: Colors.purple); @override Widget build(BuildContext context) { return Text.rich( TextSpan( children: [ TextSpan(text: "《定风波》", style: titleStyle), TextSpan(text: "苏轼", style: nameStyle), TextSpan(text: "\n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。") ] ), style:contentStyle , textAlign: TextAlign.center, ); } }
五、按钮Widget
1. 按钮的基础
Material widget库中提供了多种按钮Widget如
- FloatingActionButton
- MaterialButton
- BackButton
- CloseButton
- DrawerButton
- TextButton
- …
我们直接来对他们进行一个展示:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[FloatingActionButton(child: Text("FloatingActionButton"),onPressed: () {print("FloatingActionButton Click");},),MaterialButton(child: Text("MaterialButton"),onPressed: () {print("MaterialButton Click");},),BackButton(onPressed: () {print("BackButton Click");},),CloseButton(onPressed: () {print("CloseButton Click");},),DrawerButton(onPressed: () {print("DrawerButton Click");}),ElevatedButton(child: Text("ElevatedButton"),onPressed: () {print("ElevatedButton Click");},),FilledButton(child: Text("FilledButton"),onPressed: () {print("FilledButton Click");},),// IconButton(// icon: Icon(),// onPressed: () {// print("FilledButton Click");// },// )OutlinedButton(child: Text("OutlinedButton"),onPressed: () {print("OutlinedButton Click");},),// SegmentedButton(segments: segments, selected: selected)TextButton(child: Text("TextButton"),onPressed: () {print("TextButton Click");},)],),);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FloatingActionButton( child: Text("FloatingActionButton"), onPressed: () { print("FloatingActionButton Click"); }, ), MaterialButton( child: Text("MaterialButton"), onPressed: () { print("MaterialButton Click"); }, ), BackButton( onPressed: () { print("BackButton Click"); }, ), CloseButton( onPressed: () { print("CloseButton Click"); }, ), DrawerButton( onPressed: () { print("DrawerButton Click"); } ), ElevatedButton( child: Text("ElevatedButton"), onPressed: () { print("ElevatedButton Click"); }, ), FilledButton( child: Text("FilledButton"), onPressed: () { print("FilledButton Click"); }, ), // IconButton( // icon: Icon(), // onPressed: () { // print("FilledButton Click"); // }, // ) OutlinedButton( child: Text("OutlinedButton"), onPressed: () { print("OutlinedButton Click"); }, ), // SegmentedButton(segments: segments, selected: selected) TextButton( child: Text("TextButton"), onPressed: () { print("TextButton Click"); }, ) ], ), ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FloatingActionButton( child: Text("FloatingActionButton"), onPressed: () { print("FloatingActionButton Click"); }, ), MaterialButton( child: Text("MaterialButton"), onPressed: () { print("MaterialButton Click"); }, ), BackButton( onPressed: () { print("BackButton Click"); }, ), CloseButton( onPressed: () { print("CloseButton Click"); }, ), DrawerButton( onPressed: () { print("DrawerButton Click"); } ), ElevatedButton( child: Text("ElevatedButton"), onPressed: () { print("ElevatedButton Click"); }, ), FilledButton( child: Text("FilledButton"), onPressed: () { print("FilledButton Click"); }, ), // IconButton( // icon: Icon(), // onPressed: () { // print("FilledButton Click"); // }, // ) OutlinedButton( child: Text("OutlinedButton"), onPressed: () { print("OutlinedButton Click"); }, ), // SegmentedButton(segments: segments, selected: selected) TextButton( child: Text("TextButton"), onPressed: () { print("TextButton Click"); }, ) ], ), ); } }
2. 自定义样式
前面的按钮我们使用的都是默认样式,我们可以通过一些属性来改变按钮的样式
RaisedButton(child: Text("同意协议", style: TextStyle(color: Colors.white)),color: Colors.orange, // 按钮的颜色highlightColor: Colors.orange[700], // 按下去高亮颜色shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), // 圆角的实现onPressed: () {print("同意协议");},)RaisedButton( child: Text("同意协议", style: TextStyle(color: Colors.white)), color: Colors.orange, // 按钮的颜色 highlightColor: Colors.orange[700], // 按下去高亮颜色 shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), // 圆角的实现 onPressed: () { print("同意协议"); }, )RaisedButton( child: Text("同意协议", style: TextStyle(color: Colors.white)), color: Colors.orange, // 按钮的颜色 highlightColor: Colors.orange[700], // 按下去高亮颜色 shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), // 圆角的实现 onPressed: () { print("同意协议"); }, )
事实上这里还有一个比较常见的属性:elevation,用于控制阴影的大小,很多地方都会有这个属性,大家可以自行演示一下
六、图片Widget
图片可以让我们的应用更加丰富多彩,Flutter中使用Image组件
Image组件有很多的构造函数,我们这里主要学习两个:
Image.assets
:加载本地资源图片;Image.network
:加载网络中的图片;
1. 加载网络图片
相对来讲,Flutter中加载网络图片会更加简单,直接传入URL并不需要什么配置,所以我们先来看一下Flutter中如何加载网络图片。
我们先来看看Image有哪些属性可以设置:
const Image({...this.width, //图片的宽this.height, //图片高度this.color, //图片的混合色值this.colorBlendMode, //混合模式this.fit,//缩放模式this.alignment = Alignment.center, //对齐方式this.repeat = ImageRepeat.noRepeat, //重复方式...})const Image({ ... this.width, //图片的宽 this.height, //图片高度 this.color, //图片的混合色值 this.colorBlendMode, //混合模式 this.fit,//缩放模式 this.alignment = Alignment.center, //对齐方式 this.repeat = ImageRepeat.noRepeat, //重复方式 ... })const Image({ ... this.width, //图片的宽 this.height, //图片高度 this.color, //图片的混合色值 this.colorBlendMode, //混合模式 this.fit,//缩放模式 this.alignment = Alignment.center, //对齐方式 this.repeat = ImageRepeat.noRepeat, //重复方式 ... })
-
width
、height
:用于设置图片的宽、高,当不指定宽高时,图片会根据当前父容器的限制,尽可能的显示其原始大小,如果只设置width
、height
的其中一个,那么另一个属性默认会按比例缩放,但可以通过下面介绍的fit
属性来指定适应规则。 -
fit
:该属性用于在图片的显示空间和图片本身大小不同时指定图片的适应模式。适应模式是在BoxFit
中定义,它是一个枚举类型,有如下值:fill
:会拉伸填充满显示空间,图片本身长宽比会发生变化,图片会变形。cover
:会按图片的长宽比放大后居中填满显示空间,图片不会变形,超出显示空间部分会被剪裁。contain
:这是图片的默认适应规则,图片会在保证图片本身长宽比不变的情况下缩放以适应当前显示空间,图片不会变形。fitWidth
:图片的宽度会缩放到显示空间的宽度,高度会按比例缩放,然后居中显示,图片不会变形,超出显示空间部分会被剪裁。fitHeight
:图片的高度会缩放到显示空间的高度,宽度会按比例缩放,然后居中显示,图片不会变形,超出显示空间部分会被剪裁。none
:图片没有适应策略,会在显示空间内显示图片,如果图片比显示空间大,则显示空间只会显示图片中间部分。
-
color
和colorBlendMode
:在图片绘制时可以对每一个像素进行颜色混合处理,color
指定混合色,而colorBlendMode
指定混合模式; -
repeat
:当图片本身大小小于显示空间时,指定图片的重复规则。
我们对其中某些属性做一个演练:
- 注意,这里我用了一个Container,大家可以把它理解成一个UIView或者View,就是一个容器;
- 后面我会专门讲到这个组件的使用;
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {final imageURL = "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg";@overrideWidget build(BuildContext context) {return Center(child: Container(child:Column(children: <Widget>[HomePageNetworkImage("http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"),HomePageAssetImage("assets/images/juren.jpeg"),],)));}}// 网络图片class HomePageNetworkImage extends StatelessWidget {var imagURL = "";HomePageNetworkImage(String imageURL){this.imagURL = imageURL;}@overrideWidget build(BuildContext context) {return Image(image: NetworkImage(imagURL),width: 400,fit: BoxFit.fitHeight,alignment: Alignment.center,repeat: ImageRepeat.repeatY,color: Colors.orange,//滤镜效果colorBlendMode: BlendMode.colorDodge,//滤镜效果);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { final imageURL = "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"; @override Widget build(BuildContext context) { return Center( child: Container( child: Column( children: <Widget>[ HomePageNetworkImage("http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"), HomePageAssetImage("assets/images/juren.jpeg"), ], ) ) ); } } // 网络图片 class HomePageNetworkImage extends StatelessWidget { var imagURL = ""; HomePageNetworkImage(String imageURL){ this.imagURL = imageURL; } @override Widget build(BuildContext context) { return Image( image: NetworkImage(imagURL), width: 400, fit: BoxFit.fitHeight, alignment: Alignment.center, repeat: ImageRepeat.repeatY, color: Colors.orange,//滤镜效果 colorBlendMode: BlendMode.colorDodge,//滤镜效果 ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { final imageURL = "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"; @override Widget build(BuildContext context) { return Center( child: Container( child: Column( children: <Widget>[ HomePageNetworkImage("http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"), HomePageAssetImage("assets/images/juren.jpeg"), ], ) ) ); } } // 网络图片 class HomePageNetworkImage extends StatelessWidget { var imagURL = ""; HomePageNetworkImage(String imageURL){ this.imagURL = imageURL; } @override Widget build(BuildContext context) { return Image( image: NetworkImage(imagURL), width: 400, fit: BoxFit.fitHeight, alignment: Alignment.center, repeat: ImageRepeat.repeatY, color: Colors.orange,//滤镜效果 colorBlendMode: BlendMode.colorDodge,//滤镜效果 ); } }
2. 加载本地图片
加载本地图片稍微麻烦一点,需要将图片引入,并且进行配置:
- 在路径引入图片资源:
- 修改项目的配置:
- 更新配置:
- 注意:
若是把项目放在一个中文名称的文件路径下,则可能会导致资源引入失败;
需要把项目放在非中文的路径下
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {final imageURL = "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg";@overrideWidget build(BuildContext context) {return Center(child: Container(child:Column(children: <Widget>[HomePageNetworkImage("http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"),HomePageAssetImage("assets/images/juren.jpeg"),],)));}}// 网络图片class HomePageNetworkImage extends StatelessWidget {var imagURL = "";HomePageNetworkImage(String imageURL){this.imagURL = imageURL;}@overrideWidget build(BuildContext context) {return Image(image: NetworkImage(imagURL),width: 400,fit: BoxFit.fitHeight,alignment: Alignment.center,repeat: ImageRepeat.repeatY,color: Colors.orange,//滤镜效果colorBlendMode: BlendMode.colorDodge,//滤镜效果);}}// 本地图片class HomePageAssetImage extends StatelessWidget {var imageName = "";HomePageAssetImage(String imageName){this.imageName = imageName;}@overrideWidget build(BuildContext context) {return Image(image: AssetImage(imageName) ,alignment: Alignment.topCenter,repeat: ImageRepeat.repeatY,color: Colors.red,colorBlendMode: BlendMode.colorDodge,width: 300);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { final imageURL = "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"; @override Widget build(BuildContext context) { return Center( child: Container( child: Column( children: <Widget>[ HomePageNetworkImage("http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"), HomePageAssetImage("assets/images/juren.jpeg"), ], ) ) ); } } // 网络图片 class HomePageNetworkImage extends StatelessWidget { var imagURL = ""; HomePageNetworkImage(String imageURL){ this.imagURL = imageURL; } @override Widget build(BuildContext context) { return Image( image: NetworkImage(imagURL), width: 400, fit: BoxFit.fitHeight, alignment: Alignment.center, repeat: ImageRepeat.repeatY, color: Colors.orange,//滤镜效果 colorBlendMode: BlendMode.colorDodge,//滤镜效果 ); } } // 本地图片 class HomePageAssetImage extends StatelessWidget { var imageName = ""; HomePageAssetImage(String imageName){ this.imageName = imageName; } @override Widget build(BuildContext context) { return Image( image: AssetImage(imageName) , alignment: Alignment.topCenter, repeat: ImageRepeat.repeatY, color: Colors.red, colorBlendMode: BlendMode.colorDodge, width: 300 ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { final imageURL = "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"; @override Widget build(BuildContext context) { return Center( child: Container( child: Column( children: <Widget>[ HomePageNetworkImage("http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg"), HomePageAssetImage("assets/images/juren.jpeg"), ], ) ) ); } } // 网络图片 class HomePageNetworkImage extends StatelessWidget { var imagURL = ""; HomePageNetworkImage(String imageURL){ this.imagURL = imageURL; } @override Widget build(BuildContext context) { return Image( image: NetworkImage(imagURL), width: 400, fit: BoxFit.fitHeight, alignment: Alignment.center, repeat: ImageRepeat.repeatY, color: Colors.orange,//滤镜效果 colorBlendMode: BlendMode.colorDodge,//滤镜效果 ); } } // 本地图片 class HomePageAssetImage extends StatelessWidget { var imageName = ""; HomePageAssetImage(String imageName){ this.imageName = imageName; } @override Widget build(BuildContext context) { return Image( image: AssetImage(imageName) , alignment: Alignment.topCenter, repeat: ImageRepeat.repeatY, color: Colors.red, colorBlendMode: BlendMode.colorDodge, width: 300 ); } }
3. 实现圆角图像
在Flutter中实现圆角效果也是使用一些Widget来实现的。
3.1. 实现圆角头像
方式一:CircleAvatar
CircleAvatar可以实现圆角头像,也可以添加一个子Widget:
const CircleAvatar({Key key,this.child, // 子Widgetthis.backgroundColor, // 背景颜色this.backgroundImage, // 背景图像this.foregroundColor, // 前景颜色this.radius, // 半径this.minRadius, // 最小半径this.maxRadius, // 最大半径})const CircleAvatar({ Key key, this.child, // 子Widget this.backgroundColor, // 背景颜色 this.backgroundImage, // 背景图像 this.foregroundColor, // 前景颜色 this.radius, // 半径 this.minRadius, // 最小半径 this.maxRadius, // 最大半径 })const CircleAvatar({ Key key, this.child, // 子Widget this.backgroundColor, // 背景颜色 this.backgroundImage, // 背景图像 this.foregroundColor, // 前景颜色 this.radius, // 半径 this.minRadius, // 最小半径 this.maxRadius, // 最大半径 })
我们来实现一个圆形头像:
- 注意一:这里我们使用的是
NetworkImage
,因为backgroundImage
要求我们传入一个ImageProvider
;- ImageProvider是一个抽象类,事实上所有我们前面创建的Image对象都有包含
image
属性,该属性就是一个ImageProvider
- ImageProvider是一个抽象类,事实上所有我们前面创建的Image对象都有包含
- 注意二:这里我还在里面添加了一个文字,但是我在文字外层包裹了一个Container;
- 这里Container的作用是为了可以控制文字在其中的位置调整;
// 圆角图片class HomePageCircleAvatar extends StatelessWidget {var imageURL = "";HomePageCircleAvatar(this.imageURL);@overrideWidget build(BuildContext context) {// TODO: implement buildreturn CircleAvatar(radius: 100,backgroundImage: NetworkImage(imageURL),child: Container(alignment: Alignment(0, .5),width: 200,height: 200,child: Text("兵长利威尔")),);}}// 圆角图片 class HomePageCircleAvatar extends StatelessWidget { var imageURL = ""; HomePageCircleAvatar(this.imageURL); @override Widget build(BuildContext context) { // TODO: implement build return CircleAvatar( radius: 100, backgroundImage: NetworkImage(imageURL), child: Container( alignment: Alignment(0, .5), width: 200, height: 200, child: Text("兵长利威尔") ), ); } }// 圆角图片 class HomePageCircleAvatar extends StatelessWidget { var imageURL = ""; HomePageCircleAvatar(this.imageURL); @override Widget build(BuildContext context) { // TODO: implement build return CircleAvatar( radius: 100, backgroundImage: NetworkImage(imageURL), child: Container( alignment: Alignment(0, .5), width: 200, height: 200, child: Text("兵长利威尔") ), ); } }
方式二:ClipOval
ClipOval也可以实现圆角头像,而且通常是在只有头像时使用
class HomeContent extends StatelessWidget {@overrideWidget build(BuildContext context) {return Center(child: ClipOval(child: Image.network("https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg",width: 200,height: 200,),),);}}class HomeContent extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: ClipOval( child: Image.network( "https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg", width: 200, height: 200, ), ), ); } }class HomeContent extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: ClipOval( child: Image.network( "https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg", width: 200, height: 200, ), ), ); } }
实现方式三:Container+BoxDecoration
这种方式我们放在讲解Container时来讲这种方式
3.2. 实现圆角图片
方式一:ClipRRect
ClipRRect
用于实现圆角效果,可以设置圆角的大小。
实现代码如下,非常简单:
// 圆角图片3class HomePageClipRRect extends StatelessWidget {var imageURL = "";HomePageClipRRect(this.imageURL);@overrideWidget build(BuildContext context) {// TODO: implement buildreturn ClipRRect(borderRadius: BorderRadius.circular(10),child: Image.network(imageURL,width: 200,height: 200,),);}}// 圆角图片3 class HomePageClipRRect extends StatelessWidget { var imageURL = ""; HomePageClipRRect(this.imageURL); @override Widget build(BuildContext context) { // TODO: implement build return ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( imageURL, width: 200, height: 200, ), ); } }// 圆角图片3 class HomePageClipRRect extends StatelessWidget { var imageURL = ""; HomePageClipRRect(this.imageURL); @override Widget build(BuildContext context) { // TODO: implement build return ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( imageURL, width: 200, height: 200, ), ); } }
方式二:Container+BoxDecoration
这个在后面复习Container时再看
七、表单Widget
和用户交互的其中一种就是输入框,比如注册、登录、搜索,我们收集用户输入的内容将其提交到服务器。
1. TextField的使用
1.1 TextField的介绍
TextField
用于接收用户的文本输入,它提供了非常多的属性,我们来看一下源码:
(类似于iOS的UITextField
)
- 但是我们没必要一个个去学习,很多时候用到某个功能时去查看是否包含某个属性即可
const TextField({Key key,this.controller,this.focusNode,this.decoration = const InputDecoration(),TextInputType keyboardType,this.textInputAction,this.textCapitalization = TextCapitalization.none,this.style,this.strutStyle,this.textAlign = TextAlign.start,this.textAlignVertical,this.textDirection,this.readOnly = false,ToolbarOptions toolbarOptions,this.showCursor,this.autofocus = false,this.obscureText = false,this.autocorrect = true,this.maxLines = 1,this.minLines,this.expands = false,this.maxLength,this.maxLengthEnforced = true,this.onChanged,this.onEditingComplete,this.onSubmitted,this.inputFormatters,this.enabled,this.cursorWidth = 2.0,this.cursorRadius,this.cursorColor,this.keyboardAppearance,this.scrollPadding = const EdgeInsets.all(20.0),this.dragStartBehavior = DragStartBehavior.start,this.enableInteractiveSelection = true,this.onTap,this.buildCounter,this.scrollController,this.scrollPhysics,})const TextField({ Key key, this.controller, this.focusNode, this.decoration = const InputDecoration(), TextInputType keyboardType, this.textInputAction, this.textCapitalization = TextCapitalization.none, this.style, this.strutStyle, this.textAlign = TextAlign.start, this.textAlignVertical, this.textDirection, this.readOnly = false, ToolbarOptions toolbarOptions, this.showCursor, this.autofocus = false, this.obscureText = false, this.autocorrect = true, this.maxLines = 1, this.minLines, this.expands = false, this.maxLength, this.maxLengthEnforced = true, this.onChanged, this.onEditingComplete, this.onSubmitted, this.inputFormatters, this.enabled, this.cursorWidth = 2.0, this.cursorRadius, this.cursorColor, this.keyboardAppearance, this.scrollPadding = const EdgeInsets.all(20.0), this.dragStartBehavior = DragStartBehavior.start, this.enableInteractiveSelection = true, this.onTap, this.buildCounter, this.scrollController, this.scrollPhysics, })const TextField({ Key key, this.controller, this.focusNode, this.decoration = const InputDecoration(), TextInputType keyboardType, this.textInputAction, this.textCapitalization = TextCapitalization.none, this.style, this.strutStyle, this.textAlign = TextAlign.start, this.textAlignVertical, this.textDirection, this.readOnly = false, ToolbarOptions toolbarOptions, this.showCursor, this.autofocus = false, this.obscureText = false, this.autocorrect = true, this.maxLines = 1, this.minLines, this.expands = false, this.maxLength, this.maxLengthEnforced = true, this.onChanged, this.onEditingComplete, this.onSubmitted, this.inputFormatters, this.enabled, this.cursorWidth = 2.0, this.cursorRadius, this.cursorColor, this.keyboardAppearance, this.scrollPadding = const EdgeInsets.all(20.0), this.dragStartBehavior = DragStartBehavior.start, this.enableInteractiveSelection = true, this.onTap, this.buildCounter, this.scrollController, this.scrollPhysics, })
我们来学习几个比较常见的属性:
- 一些属性比较简单:
keyboardType
键盘的类型,style
设置样式,textAlign
文本对齐方式,maxLength
最大显示行数等等; decoration
:用于设置输入框相关的样式- icon:设置左边显示的图标
- labelText:在输入框上面显示一个提示的文本
- hintText:显示提示的占位文字
- border:输入框的边框,默认底部有一个边框,可以通过InputBorder.none删除掉
- filled:是否填充输入框,默认为false
- fillColor:输入框填充的颜色
controller
:onChanged
:监听输入框内容的改变,传入一个回调函数onSubmitted
:点击键盘中右下角的down时,会回调的一个函数
1.2 TextField的样式以及监听
我们来演示一下TextField
的decoration
属性以及监听:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Center(child: Container(child:HomePageTextField(),));}}// 表单TextFieldclass HomePageTextField extends StatefulWidget {@overrideHomePageTextFieldState createState() => HomePageTextFieldState();}class HomePageTextFieldState extends State<HomePageTextField> {@overrideWidget build(BuildContext context) {return TextField(decoration: InputDecoration(icon: Icon(Icons.people),labelText: "username",hintText: "请输入用户名",border: InputBorder.none,filled: true,fillColor: Colors.lightGreen),onChanged: (value) {print("onChanged:$value");},onSubmitted: (value) {print("onSubmitted:$value");},);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageTextField(), ) ); } } // 表单TextField class HomePageTextField extends StatefulWidget { @override HomePageTextFieldState createState() => HomePageTextFieldState(); } class HomePageTextFieldState extends State<HomePageTextField> { @override Widget build(BuildContext context) { return TextField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "username", hintText: "请输入用户名", border: InputBorder.none, filled: true, fillColor: Colors.lightGreen ), onChanged: (value) { print("onChanged:$value"); }, onSubmitted: (value) { print("onSubmitted:$value"); }, ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageTextField(), ) ); } } // 表单TextField class HomePageTextField extends StatefulWidget { @override HomePageTextFieldState createState() => HomePageTextFieldState(); } class HomePageTextFieldState extends State<HomePageTextField> { @override Widget build(BuildContext context) { return TextField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "username", hintText: "请输入用户名", border: InputBorder.none, filled: true, fillColor: Colors.lightGreen ), onChanged: (value) { print("onChanged:$value"); }, onSubmitted: (value) { print("onSubmitted:$value"); }, ); } }
1.3 TextField的controller
我们可以给TextField
添加一个控制器(Controller
),可以使用它设置文本的初始值,也可以使用它来监听文本的改变;
事实上,如果我们没有为TextField
提供一个Controller
,那么会Flutter会默认创建一个TextEditingController
的,这个结论可以通过阅读源码得到:
@overridevoid initState() {super.initState();// ...其他代码if (widget.controller == null)_controller = TextEditingController();}@override void initState() { super.initState(); // ...其他代码 if (widget.controller == null) _controller = TextEditingController(); }@override void initState() { super.initState(); // ...其他代码 if (widget.controller == null) _controller = TextEditingController(); }
我们也可以自己来创建一个Controller
控制一些内容:
class HomePageTextFieldState extends State<HomePageTextField> {final textEditingController = TextEditingController();@overridevoid initState() {// TODO: implement initStatesuper.initState();// 1.设置默认值textEditingController.text = "Hello World";// 2.监听文本框textEditingController.addListener(() {print("textEditingController:${textEditingController.text}");});}@overrideWidget build(BuildContext context) {return TextField(controller: textEditingController,decoration: InputDecoration(icon: Icon(Icons.people),labelText: "username",hintText: "请输入用户名",border: InputBorder.none,filled: true,fillColor: Colors.lightGreen),onChanged: (value) {print("onChanged:$value");},onSubmitted: (value) {print("onSubmitted:$value");},);}}class HomePageTextFieldState extends State<HomePageTextField> { final textEditingController = TextEditingController(); @override void initState() { // TODO: implement initState super.initState(); // 1.设置默认值 textEditingController.text = "Hello World"; // 2.监听文本框 textEditingController.addListener(() { print("textEditingController:${textEditingController.text}"); }); } @override Widget build(BuildContext context) { return TextField( controller: textEditingController, decoration: InputDecoration( icon: Icon(Icons.people), labelText: "username", hintText: "请输入用户名", border: InputBorder.none, filled: true, fillColor: Colors.lightGreen ), onChanged: (value) { print("onChanged:$value"); }, onSubmitted: (value) { print("onSubmitted:$value"); }, ); } }class HomePageTextFieldState extends State<HomePageTextField> { final textEditingController = TextEditingController(); @override void initState() { // TODO: implement initState super.initState(); // 1.设置默认值 textEditingController.text = "Hello World"; // 2.监听文本框 textEditingController.addListener(() { print("textEditingController:${textEditingController.text}"); }); } @override Widget build(BuildContext context) { return TextField( controller: textEditingController, decoration: InputDecoration( icon: Icon(Icons.people), labelText: "username", hintText: "请输入用户名", border: InputBorder.none, filled: true, fillColor: Colors.lightGreen ), onChanged: (value) { print("onChanged:$value"); }, onSubmitted: (value) { print("onSubmitted:$value"); }, ); } }
2. Form表单的使用
在我们开发注册、登录页面时,通常会有多个表单需要同时获取内容或者进行一些验证,如果对每一个TextField都分别进行验证,是一件比较麻烦的事情。
做过前端的开发知道,我们可以将多个input标签放在一个form里面,Flutter也借鉴了这样的思想:我们可以通过Form对输入框进行分组,统一进行一些操作。
2.1 Form表单的基本使用
Form
表单也是一个Widget,可以在里面放入我们的输入框。
但是Form表单中输入框必须是FormField类型的
- 我们查看刚刚学过的
TextField
是继承自StatefulWidget,并不是一个FormField类型; - 我们可以使用
TextFormField
,它的使用类似于TextField,并且是继承自FormField的;
我们通过Form
的包裹,来实现一个注册的页面:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Center(child: Container(child:HomePageForm(),));}}// 表单TextFieldclass HomePageForm extends StatefulWidget {@overrideHomePageFormState createState() => HomePageFormState();}class HomePageFormState extends State<HomePageForm> {@overrideWidget build(BuildContext context) {return Form(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[HomePageUserNameTextFormField(),HomePagePasswordTextFormField(),SizedBox(height: 16,),Container(width: double.infinity,height: 44,child: MaterialButton(color: Colors.lightGreen,child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),),onPressed: () {print("点击了注册按钮");},),)],),);}}class HomePageUserNameTextFormField extends StatelessWidget {@overrideWidget build(BuildContext context) {return TextFormField(decoration: InputDecoration(icon: Icon(Icons.people),labelText: "用户名或手机号"),);}}class HomePagePasswordTextFormField extends StatelessWidget {HomePagePasswordTextFormField();@overrideWidget build(BuildContext context) {return TextFormField(obscureText: true,decoration: InputDecoration(icon: Icon(Icons.lock),labelText: "密码"),);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageForm(), ) ); } } // 表单TextField class HomePageForm extends StatefulWidget { @override HomePageFormState createState() => HomePageFormState(); } class HomePageFormState extends State<HomePageForm> { @override Widget build(BuildContext context) { return Form( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ HomePageUserNameTextFormField(), HomePagePasswordTextFormField(), SizedBox(height: 16,), Container( width: double.infinity, height: 44, child: MaterialButton( color: Colors.lightGreen, child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),), onPressed: () { print("点击了注册按钮"); }, ), ) ], ), ); } } class HomePageUserNameTextFormField extends StatelessWidget { @override Widget build(BuildContext context) { return TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), ); } } class HomePagePasswordTextFormField extends StatelessWidget { HomePagePasswordTextFormField(); @override Widget build(BuildContext context) { return TextFormField( obscureText: true, decoration: InputDecoration( icon: Icon(Icons.lock), labelText: "密码" ), ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageForm(), ) ); } } // 表单TextField class HomePageForm extends StatefulWidget { @override HomePageFormState createState() => HomePageFormState(); } class HomePageFormState extends State<HomePageForm> { @override Widget build(BuildContext context) { return Form( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ HomePageUserNameTextFormField(), HomePagePasswordTextFormField(), SizedBox(height: 16,), Container( width: double.infinity, height: 44, child: MaterialButton( color: Colors.lightGreen, child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),), onPressed: () { print("点击了注册按钮"); }, ), ) ], ), ); } } class HomePageUserNameTextFormField extends StatelessWidget { @override Widget build(BuildContext context) { return TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), ); } } class HomePagePasswordTextFormField extends StatelessWidget { HomePagePasswordTextFormField(); @override Widget build(BuildContext context) { return TextFormField( obscureText: true, decoration: InputDecoration( icon: Icon(Icons.lock), labelText: "密码" ), ); } }
2.2 保存和获取表单数据
有了表单后,我们需要在点击注册时,可以同时获取和保存表单中的数据,怎么可以做到呢?
- 1、需要监听注册按钮的点击,在之前我们已经监听的
onPressed
传入的回调中来做即可。(当然,如果嵌套太多,我们待会儿可以将它抽取到一个单独的方法中) - 2、监听到按钮点击时,同时获取
用户名
和密码
的表单信息。
如何同时获取用户名
和密码
的表单信息?
- 如果我们调用
Form的State对象
的save
方法,就会调用Form中放入的TextFormField
的onSave
回调:
TextFormField(decoration: InputDecoration(icon: Icon(Icons.people),labelText: "用户名或手机号"),onSaved: (value) {print("用户名:$value");},),TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), onSaved: (value) { print("用户名:$value"); }, ),TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), onSaved: (value) { print("用户名:$value"); }, ),
- 但是,我们有没有办法可以在点击按钮时,拿到
Form对象
来调用它的save方法呢?
知识点:在Flutter如何可以获取一个通过一个引用获取一个StatefulWidget的State对象呢?
答案:通过绑定一个GlobalKey
即可。
案例代码演练:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Center(child: Container(child:HomePageForm(),));}}// 表单TextFieldclass HomePageForm extends StatefulWidget {@overrideHomePageFormState createState() => HomePageFormState();}class HomePageFormState extends State<HomePageForm> {final registerFormKey = GlobalKey<FormState>();var username = "";var password = "";void registerForm(){registerFormKey.currentState?.save();print("userName:$username,password:$password");}@overrideWidget build(BuildContext context) {return Form(key: registerFormKey,child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[TextFormField(decoration: InputDecoration(icon: Icon(Icons.people),labelText: "用户名或手机号"),onSaved: (value) {print("onSaved:$value");this.username = value as String;},),TextFormField(obscureText: true,decoration: InputDecoration(icon: Icon(Icons.lock),labelText: "密码"),onSaved: (value) {print("onSaved:$value");this.password = value as String;},),SizedBox(height: 16),Container(width: double.infinity,height: 44,child: MaterialButton(color: Colors.lightGreen,child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),),onPressed: registerForm,),)],),);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageForm(), ) ); } } // 表单TextField class HomePageForm extends StatefulWidget { @override HomePageFormState createState() => HomePageFormState(); } class HomePageFormState extends State<HomePageForm> { final registerFormKey = GlobalKey<FormState>(); var username = ""; var password = ""; void registerForm(){ registerFormKey.currentState?.save(); print("userName:$username,password:$password"); } @override Widget build(BuildContext context) { return Form( key: registerFormKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), onSaved: (value) { print("onSaved:$value"); this.username = value as String; }, ), TextFormField( obscureText: true, decoration: InputDecoration( icon: Icon(Icons.lock), labelText: "密码" ), onSaved: (value) { print("onSaved:$value"); this.password = value as String; }, ), SizedBox(height: 16), Container( width: double.infinity, height: 44, child: MaterialButton( color: Colors.lightGreen, child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),), onPressed: registerForm, ), ) ], ), ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageForm(), ) ); } } // 表单TextField class HomePageForm extends StatefulWidget { @override HomePageFormState createState() => HomePageFormState(); } class HomePageFormState extends State<HomePageForm> { final registerFormKey = GlobalKey<FormState>(); var username = ""; var password = ""; void registerForm(){ registerFormKey.currentState?.save(); print("userName:$username,password:$password"); } @override Widget build(BuildContext context) { return Form( key: registerFormKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), onSaved: (value) { print("onSaved:$value"); this.username = value as String; }, ), TextFormField( obscureText: true, decoration: InputDecoration( icon: Icon(Icons.lock), labelText: "密码" ), onSaved: (value) { print("onSaved:$value"); this.password = value as String; }, ), SizedBox(height: 16), Container( width: double.infinity, height: 44, child: MaterialButton( color: Colors.lightGreen, child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),), onPressed: registerForm, ), ) ], ), ); } }
2.3 验证填写的表单数据
在表单中,我们可以添加验证器
,如果不符合某些特定的规则,那么给用户一定的提示信息
比如我们需要账号和密码有这样的规则:账号和密码都不能为空。
按照如下步骤就可以完成整个验证过程:
- 1、为
TextFormField
添加validator
的回调函数; - 2、调用Form的State对象的
validate
方法,就会回调validator
传入的函数;
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(showSemanticsDebugger: false,home: HomePage(),);}}class HomePage extends StatelessWidget {@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(appBar: AppBar(title: Text("我的导航栏"),backgroundColor: Colors.green,),body: HomePageBody(),);}}class HomePageBody extends StatelessWidget {@overrideWidget build(BuildContext context) {return Center(child: Container(child:HomePageForm(),));}}// 表单TextFieldclass HomePageForm extends StatefulWidget {@overrideHomePageFormState createState() => HomePageFormState();}class HomePageFormState extends State<HomePageForm> {final registerFormKey = GlobalKey<FormState>();var username = "";var password = "";void registerForm(){registerFormKey.currentState?.validate();registerFormKey.currentState?.save();print("userName:$username,password:$password");}@overrideWidget build(BuildContext context) {return Form(key: registerFormKey,child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[TextFormField(decoration: InputDecoration(icon: Icon(Icons.people),labelText: "用户名或手机号"),onSaved: (value) {print("onSaved:$value");this.username = value as String;},validator: (value){if (value!.isEmpty){return "账号不能为空";}return null;},),TextFormField(obscureText: true,decoration: InputDecoration(icon: Icon(Icons.lock),labelText: "密码"),onSaved: (value) {print("onSaved:$value");this.password = value as String;},validator: (value){if (value!.isEmpty){return "密码不能为空";}return null;},),SizedBox(height: 16),Container(width: double.infinity,height: 44,child: MaterialButton(color: Colors.lightGreen,child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),),onPressed: registerForm,),)],),);}}import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageForm(), ) ); } } // 表单TextField class HomePageForm extends StatefulWidget { @override HomePageFormState createState() => HomePageFormState(); } class HomePageFormState extends State<HomePageForm> { final registerFormKey = GlobalKey<FormState>(); var username = ""; var password = ""; void registerForm(){ registerFormKey.currentState?.validate(); registerFormKey.currentState?.save(); print("userName:$username,password:$password"); } @override Widget build(BuildContext context) { return Form( key: registerFormKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), onSaved: (value) { print("onSaved:$value"); this.username = value as String; }, validator: (value){ if (value!.isEmpty){ return "账号不能为空"; } return null; }, ), TextFormField( obscureText: true, decoration: InputDecoration( icon: Icon(Icons.lock), labelText: "密码" ), onSaved: (value) { print("onSaved:$value"); this.password = value as String; }, validator: (value){ if (value!.isEmpty){ return "密码不能为空"; } return null; }, ), SizedBox(height: 16), Container( width: double.infinity, height: 44, child: MaterialButton( color: Colors.lightGreen, child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),), onPressed: registerForm, ), ) ], ), ); } }import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( showSemanticsDebugger: false, home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("我的导航栏"), backgroundColor: Colors.green, ), body: HomePageBody(), ); } } class HomePageBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: HomePageForm(), ) ); } } // 表单TextField class HomePageForm extends StatefulWidget { @override HomePageFormState createState() => HomePageFormState(); } class HomePageFormState extends State<HomePageForm> { final registerFormKey = GlobalKey<FormState>(); var username = ""; var password = ""; void registerForm(){ registerFormKey.currentState?.validate(); registerFormKey.currentState?.save(); print("userName:$username,password:$password"); } @override Widget build(BuildContext context) { return Form( key: registerFormKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( decoration: InputDecoration( icon: Icon(Icons.people), labelText: "用户名或手机号" ), onSaved: (value) { print("onSaved:$value"); this.username = value as String; }, validator: (value){ if (value!.isEmpty){ return "账号不能为空"; } return null; }, ), TextFormField( obscureText: true, decoration: InputDecoration( icon: Icon(Icons.lock), labelText: "密码" ), onSaved: (value) { print("onSaved:$value"); this.password = value as String; }, validator: (value){ if (value!.isEmpty){ return "密码不能为空"; } return null; }, ), SizedBox(height: 16), Container( width: double.infinity, height: 44, child: MaterialButton( color: Colors.lightGreen, child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),), onPressed: registerForm, ), ) ], ), ); } }