flutter 组件学习

501 阅读2分钟

Image

Image 构造方法

  • Image:通过ImageProvider来加载图片
  • Image.asset:用来加载本地资源图片
  • Image.file:用来加载本地(File文件)图片
  • Image.network:用来加载网络图片
  • Image.memory:用来加载Uint8List资源(byte数组)图片

1.Image

Image 的一个参数是 ImageProvider,基本上所有形式的图片加载都是依赖它,这个类里面就是实现图片加载的原理。用法如下:

new Image(image: new AssetImage('images/logo.png'));
new Image(image: new NetworkImage('http://n.sinaimg.cn/sports/2_img/upload/cf0d0fdd/107/w1024h683/20181128/pKtl-hphsupx4744393.jpg'))

2.Image.asset

加载一个本地资源图片,和 Android 一样,有多种分辨率的图片可供选择,但是沿袭的是 iOS 的图片风格,分为 1x,2x,3x,具体做法是在项目的根目录下创建两个文件夹,如下图所示: 然后需要在 pubspec.yaml 文件中声明一下:

flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
  assets:
    - images/logo.png
    - images/2.0x/logo.png
    - images/3.0x/logo.png

用法如下:

new Image.asset('images/logo.png')

3. Image.file

加载一个本地 File 图片,比如相册中的图片,用法如下

new Image.file(new File('/storage/xxx/xxx/test.jpg'))

4. Image.network

加载一个网络图片,用法如下:

new Image.network('http://n.sinaimg.cn/sports/2_img/upload/cf0d0fdd/107/w1024h683/20181128/pKtl-hphsupx4744393.jpg')

5. FadeInImage

有的时候我们需要像Android那样使用一个占位图或者图片加载出错时显示某张特定的图片,这时候需要用到 FadeInImage 这个组件:

new FadeInImage.assetNetwork(
  placeholder: 'images/logo.png',
  image: imageUrl,
  width: 120,
  fit: BoxFit.fitWidth,
)

new FadeInImage.memoryNetwork(
  placeholder: kTransparentImage,
  image: imageUrl,
  width: 120,
  fit: BoxFit.fitWidth,
)

6. 常用属性

名称功能
width & height
fit图片位置 BoxFit.contain , .cover , .fill , .fitHeight , .fitWidth
repeat图片重复
alignment用来控制图片摆放的位置

CupertinoTabScaffold

IOS风格底部栏

class CupertinoApp extends StatefulWidget {
  @override
  _CupertinoAppState createState() => _CupertinoAppState();
}

class _CupertinoAppState extends State<CupertinoApp> {
	var _title = '首页';
	@override
	Widget build(BuildContext context) {
		return Scaffold(
			appBar: AppBar(title : Text(_title)),
			body: CupertinoTabScaffold(
				tabBar: CupertinoTabBar(
					items: [
						BottomNavigationBarItem(
							icon: Icon(CupertinoIcons.home,),
							title: Text("首页"),
						),
						BottomNavigationBarItem(
							icon: Icon(CupertinoIcons.settings,),
							title: Text("设置"),
						),
					],
					activeColor: Colors.red,
					inactiveColor: Color(0xff333333),
					backgroundColor: Color(0xfff1f1f1),
					iconSize: 28.0,
					onTap: (index){
						setState(() {
							switch(index){
								case 0 : 
									_title = '首页';
									return;
								case 1:
									_title = '页面1';
							}
						});
					},
				), 
				tabBuilder:  (context, index) {
					return CupertinoTabView(
						builder: (context) {
							switch (index) {
								case 0:
									return Page1();
									break; 
								case 1:
									return Page2(context);
									break;
							}
						},
					);
				}
			),
		);
	}
}