首页 > 建站教程 > APP开发,混合APP >  Flutter笔记32:ImageFile本地资源图片正文

Flutter笔记32:ImageFile本地资源图片

ImageFile本地资源图片,和AssetImage不同,前者是显示手机中存储的图片,而后者是显示app内的图片,需要在pubspec.yaml中设置图片路径。这里采用image_picker插件,选择图片,并且用ImageFile显示出来:

1、在pubspec.yaml中添加image_picker:
pubspec.yaml
image_picker: ^0.6.7+11
2、用ImageFile显示本地图片:
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

void main() => runApp(MyApp());

//ImageFile本地资源图片,和AssetImage不同,前者是显示手机中存储的图片,而后者是显示app内的图片,需要在pubspec.yaml中设置图片路径



class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  //File属于IO库
  File _image;

  //获取图片
  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ImageFile本地资源图片',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ImageFile本地资源图片'),
        ),
        body: Center(
          child: Column(
            children: [
              Center(
                child: _image == null
                    ? Text('您还未选择任何图片')
                    : Image.file(
                        _image,
                        scale: .5,
                        fit: BoxFit.cover,
                      ),
              ),
              FlatButton(
                onPressed: getImage,
                child: Text('选择图片'),
              )
            ],
          ),
        ),
      ),
    );
  }
}