[Flutter] A Beginner’s Study Notes
Flutter is Google’s open source framework for building cross-platform mobile apps with faithful rendering and high performance. Developers use Dart to write one codebase that runs on both iOS and Android. Flutter provides many widgets and APIs, and supports adding native extensions.
![[Flutter] A Beginner’s Study Notes](https://qnimg.vadxq.com/blog/2019/flutter-cover.png)
Flutter is Google’s open source framework for building cross-platform mobile apps with faithful rendering and high performance. Developers use Dart to write one codebase that runs on both iOS and Android. Flutter provides many widgets and APIs, and supports adding native extensions.
The following are personal study notes
Text Widget
TextAlign property: left (left alignment), center (center alignment), right (right alignment)
maxLines property: Set the maximum number of displayed lines
overflow property: clip: the remaining text is not displayed; ellipsis: the ellipsis is displayed;
fade: Overflowing text gradually fades out.
style property: see https://docs.flutter.io/flutter/painting/TextStyle-class.html
Container widget
Alignment property
bottomCenter:下部居中对齐。
botomLeft: 下部左对齐。
bottomRight:下部右对齐。
center:纵横双向居中对齐。
centerLeft:纵向居中横向居左对齐。
centerRight:纵向居中横向居右对齐。
topLeft:顶部左侧对齐。
topCenter:顶部居中对齐。
topRight: 顶部居左对齐。Set width, height and color properties
width:500.0,
height:400.0,
color: Colors.lightBlue,padding property
margin property
decoration property: set the container’s background and border
decoration:new BoxDecoration( // 渐变
gradient:const LinearGradient(
colors:[Colors.lightBlue,Colors.greenAccent,Colors.purple] // 颜色
),
border:Border.all(width:2.0,color:Colors.red) // 边框
),Image widget
Image source
Image.asset:加载资源图片,相对路径。
Image.network:网络资源图片。
Image.file:加载本地图片,绝对路径。
Image.memory: 加载Uint8List资源图片。fit property: control how an image is scaled to fit
BoxFit.fill:全图显示,图片会被拉伸,并充满父容器。
BoxFit.contain:全图显示,显示原比例,可能会有空隙。
BoxFit.cover:显示可能拉伸,可能裁切,充满(图片要充满整个容器,还不变形)。
BoxFit.fitWidth:宽度充满(横向充满),显示可能拉伸,可能裁切。
BoxFit.fitHeight :高度充满(竖向充满),显示可能拉伸,可能裁切。
BoxFit.scaleDown:效果和contain差不多,但是此属性不允许显示超过源图片大小,可小不可大colorBlendMode (image blending mode)
color:是要混合的颜色,如果你只设置color是没有意义的。
colorBlendMode:是混合模式,相当于我们如何混合。repeat: repeating an image
ImageRepeat.repeat : 横向和纵向都进行重复,直到铺满整个画布。
ImageRepeat.repeatX: 横向重复,纵向不重复。
ImageRepeat.repeatY:纵向重复,横向不重复。ListView widget
demo
body: new ListView(
children:<Widget>[
new ListTile(
leading: new Icon(Icons.access_time),
title: new Text('access_time')
)
]
),Use of image list: Replace ListTile with Image Widget
Use of horizontal lists
Set the ListView’s scrollDirection property
Axis.horizontal:横向滚动或者叫水平方向滚动。
Axis.vertical:纵向滚动或者叫垂直方向滚动。
child:new ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
new Container(
width:180.0,
color: Colors.lightBlue,
),
new Container(
width:180.0,
color: Colors.amber,
),
new Container(
width:180.0,
color: Colors.deepOrange,
),
],
)Use of dynamic lists
Usage of List type:
var myList = List(): 非固定长度的声明。
var myList = List(2): 固定长度的声明。
var myList= List<String>():固定类型的声明方式。
var myList = [1,2,3]: 对List直接赋值。
动态列表 ListView.builder()GridView widget
padding: The inner spacing, which should be familiar.
crossAxisSpacing: The spacing between grid items along the cross axis.
crossAxisCount: The number of columns of the grid, equivalent to the number of grids placed in one row.
demo
body:GridView.count(
padding:const EdgeInsets.all(20.0),
crossAxisSpacing: 10.0,
crossAxisCount: 3,
children: <Widget>[
const Text('I am Jspang'),
const Text('I love Web'),
const Text('jspang.com'),
const Text('我喜欢玩游戏'),
const Text('我喜欢看书'),
const Text('我喜欢吃火锅')
],
)Horizontal layout with Row
Flexible sizing with Expanded
demo
body:new Row(
children: <Widget>[
Expanded(
child:new RaisedButton(
onPressed: (){
},
color:Colors.redAccent,
child:new Text('红色按钮')
)
),
Expanded(child:new RaisedButton(
onPressed: (){
},
color:Colors.orangeAccent,
child: new Text('黄色按钮'),
)
),
Expanded(child:new RaisedButton(
onPressed: (){
},
color:Colors.pinkAccent,
child:new Text('粉色按钮')
)
)
],
)Fixed sizing
body:new Row(
children: <Widget>[
new RaisedButton(
onPressed: (){
},
color:Colors.redAccent,
child:new Text('红色按钮')
),Vertical layout with Column
body:Column(
children: <Widget>[
Text('I am JSPang'),
Text('my website is jspang.com'),
Text('I love coding')
],
)CrossAxisAlignment.star:居左对齐。
CrossAxisAlignment.end:居右对齐。
CrossAxisAlignment.center:居中对齐。
main轴:如果你用column组件,那垂直就是主轴,如果你用Row组件,那水平就是主轴。
cross轴:cross轴我们称为幅轴,是和主轴垂直的方向。比如Row组件,那垂直就是幅轴,Column组件的幅轴就是水平方向的。body:Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('I am JSPang'),
Text('my website is jspang.com'),
Text('I love coding')
],
)Horizontally centered relative to screen
body:Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(child:Text('I am JSPang')),
Center(child:Text('my website is jspang.com')),
Center(child:Text('I love coding'))
],
)Using Expanded
body:Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(child:Text('I am JSPang')),
Expanded(child:Center(child:Text('my website is jspang.com'))),
Center(child:Text('I love coding'))
],
)Overlapping widgets with Stack
The alignment property controls how children are positioned in a Stack and is useful when overlapping two widgets. It uses X-axis and Y-axis values from 0 to 1, measured from the top-left corner of the parent container.
Using CircleAvatar, commonly used for profile pictures
new CircleAvatar(
backgroundImage: new NetworkImage(''),
radius: 100.0,
),Positioned component
bottom: 距离层叠组件下边的距离
left:距离层叠组件左边的距离
top:距离层叠组件上边的距离
right:距离层叠组件右边的距离
width: 层叠定位组件的宽度
height: 层叠定位组件的高度demo
var stack = new Stack(
children: <Widget>[
new CircleAvatar(
backgroundImage: new NetworkImage('http://jspang.com/static//myimg/blogtouxiang.jpg'),
radius: 100.0,
),
new Positioned(
top:10.0,
left:10.0,
child: new Text('JSPang.com'),
),
new Positioned(
bottom:10.0,
right:10.0,
child: new Text('技术胖'),
)
],
);Card layout
var card = new Card(
child: Column(
children: <Widget>[
ListTile(
title:new Text('吉林省吉林市昌邑区',style: TextStyle(fontWeight: FontWeight.w500),),
subtitle: new Text('技术胖:1513938888'),
leading: new Icon(Icons.account_box,color: Colors.lightBlue,),
),
new Divider(),
ListTile(
title:new Text('北京市海淀区中国科技大学',style: TextStyle(fontWeight: FontWeight.w500),),
subtitle: new Text('胜宏宇:1513938888'),
leading: new Icon(Icons.account_box,color: Colors.lightBlue,),
),
new Dvider(),
],
),
)Route hierarchy
RaisedButton按钮组件
child:可以放入容器,图标,文字。让你构建多彩的按钮。
onPressed:点击事件的相应,一般会调用Navigator组件。
Navigator.push 和 Navigator.pop
Navigator.push:是跳转到下一个页面,它要接受两个参数一个是上下文context,另一个是要跳转的函数。
Navigator.pop:是返回到上一个页面,使用时传递一个context(上下文)参数,使用时要注意的是,你必须是有上级页面的,也就是说上级页面使用了Navigator.push。Passing and receiving navigation parameters
Declare data structure class:
In Dart, classes can model data. For example, a product has a title and a description. Here, the Product class has two string fields: title and description.
title: is the product title.
description: Product details description
The code is as follows:
class Product{
final String title; //商品标题
final String description; //商品描述
Product(this.title,this.description);
}Build a product list
void main(){
runApp(MaterialApp(
title:'数据传递案例',
home:ProductList(
products:List.generate(
20,
(i)=>Product('商品 $i','这是一个商品详情,编号为:$i')
),
)
));
}Passing navigation arguments: use Navigator with a MaterialPageRoute to pass the data.
Navigator.push(
context,
MaterialPageRoute(
builder:(context)=>new ProductDetail(product:products[index])
)
);To receive and display the data on the destination screen, define a ProductDetail widget whose constructor accepts the arguments.
import 'package:flutter/material.dart';
//传递的数据结构,也可以理解为对商品数据的抽象
class Product{
final String title; //商品标题
final String description; //商品描述
Product(this.title,this.description);
}
void main(){
runApp(MaterialApp(
title:'数据传递案例',
home:ProductList(
products:List.generate(
20,
(i)=>Product('商品 $i','这是一个商品详情,编号为:$i')
),
)
));
}
class ProductList extends StatelessWidget{
final List<Product> products;
ProductList({Key key,@required this.products}):super(key:key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('商品列表')),
body:ListView.builder(
itemCount:products.length,
itemBuilder: (context,index){
return ListTile(
title:Text(products[index].title),
onTap:(){
Navigator.push(
context,
MaterialPageRoute(
builder:(context)=>new ProductDetail(product:products[index])
)
);
}
);
},
)
);
}
}
class ProductDetail extends StatelessWidget {
final Product product;
ProductDetail({Key key ,@required this.product}):super(key:key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title:Text('${product.title}'),
),
body:Center(child: Text('${product.description}'),)
);
}
}Navigate to another screen and return data
Asynchronous requests and awaits: async...await
SnackBar的使用
SnackBar是用户操作后,显示提示信息的一个控件,类似Tost,会自动隐藏。SnackBar是以Scaffold的showSnackBar方法来进行显示的。
Scaffold.of(context).showSnackBar(SnackBar(content:Text('$result')));How to return data
To return data, pass it as the second argument when popping the route.
Navigator.pop(context,'xxxx'); //xxx is the returned parameter
import 'package:flutter/material.dart';
void main(){
runApp(MaterialApp(
title:'页面跳转返回数据',
home:FirstPage()
));
}
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(title:Text("找小姐姐要电话")),
body:Center(
child: RouteButton(),
)
);
}
}
//跳转的Button
class RouteButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed:(){
_navigateToXiaoJieJie(context);
},
child: Text('去找小姐姐'),
);
}
_navigateToXiaoJieJie(BuildContext context) async{ //async是启用异步方法
final result = await Navigator.push(//等待
context,
MaterialPageRoute(builder: (context)=> XiaoJieJie())
);
Scaffold.of(context).showSnackBar(SnackBar(content:Text('$result')));
}
}
class XiaoJieJie extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
title:Text('我是小姐姐')
),
body:Center(
child:Column(
children: <Widget>[
RaisedButton(
child: Text('大长腿小姐姐'),
onPressed: (){
Navigator.pop(context,'大长腿:1511008888');
},
) ,
RaisedButton(
child: Text('小蛮腰小姐姐'),
onPressed: (){
Navigator.pop(context,'大长腿:1511009999');
},
) ,
],
)
) ,
);
}
}Static assets and project images
pubspec.yaml
If you want to configure project resource files, you need to use the pubspec.yaml file, and the resource files need to be declared here.
For example, if a new images folder is created in the project root directory, and a picture is placed under the folder, and the name of the picture is blogtouxiang.jpg, then we must write the following code in the pubspec.yaml file to declare it.
assets:
- images/blogtouxiang.jpgUse project image assets
With the declaration, we can directly reference this file in the project. The simplest code structure is used here, using only one picture. The code is as follows:
import 'package:flutter/material.dart';
void main()=>runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Image.asset('images/blogtouxiang.jpg'),
);
}
}Building a Flutter app for release
Configuration
The /android/app/src/main/res/AndroidManifest.xml file under the project root
This file is mainly used to configure the name, icon and system permissions of the APP. It is located in the directory:
项目根目录/android/app/src/main/AndroidManifest.xml
android:label="flutter_app" //配置APP的名称,支持中文
android:icon="@mipmap/ic_launcher" //APP图标的文件名称Generate keystore
D:\Program\Android\'Android Studio'\jre\bin\keytool -genkey -v -keystore D:\key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
After you have this key.jks file, you can go to the android folder in the project directory, create a file named key.properties, open it and paste the following code.
storePassword=<password from previous step> //输入上一步创建KEY时输入的 密钥库 密码
keyPassword=<password from previous step> //输入上一步创建KEY时输入的 密钥 密码
keyAlias=key
storeFile=<E:/key.jks> //key.jks的存放路径Configure signing
After generating the key, configure it in build.gradle. The steps below mostly involve copying and pasting; you don’t need to understand every file in detail to follow them.
First item:
Open the project’s /android/app/build.gradle file and add the following code before the android{ line:
def keystorePropertiesFile = rootProject.file("key.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))Replace this code
buildTypes {
release {
signingConfig signingConfigs.debug
}
}With:
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}Generate an APK
flutter build apk