[ flutter ] file_picker包, 实现文件选择

import 'dart:io';

import "package:flutter/material.dart";
import 'package:oktoast/oktoast.dart';
import 'package:file_picker/file_picker.dart';

void main() {
  runApp(const MainLayout());
}

class MainLayout extends StatefulWidget {
  const MainLayout({super.key});

  @override
  State<MainLayout> createState() => _MainLayoutState();
}

class _MainLayoutState extends State<MainLayout> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          appBarTheme: const AppBarTheme(
              backgroundColor: Colors.blue, foregroundColor: Colors.white)),
      debugShowCheckedModeBanner: false,
      home: OKToast(
          child: Scaffold(
        appBar: AppBar(title: const Text('首页')),
        body: const BodyLayout(),
      )),
    );
  }
}

class BodyLayout extends StatefulWidget {
  const BodyLayout({super.key});

  @override
  State<BodyLayout> createState() => _BodyLayoutState();
}

class _BodyLayoutState extends State<BodyLayout> {
  File? _selectedImage;

  // 选择单个文件
  Future<void> _chooseFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.image, // 只允许选择图片
      allowMultiple: false, // 不允许选择多张
      allowCompression: true, //
    );

    if (result != null && result.files.isNotEmpty) {
      // 获取图片路径并创建File对象
      setState(() {
        _selectedImage = File(result.files.single.path!);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      color: const Color.fromRGBO(240, 244, 245, 1),
      padding: const EdgeInsets.all(16),
      child: Wrap(
        children: [
          ElevatedButton(onPressed: _chooseFile, child: const Text("选择文件")),
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: _selectedImage != null
                ? Image.file(
                    _selectedImage!,
                    fit: BoxFit.cover, // 保持图片比例
                    errorBuilder: (context, error, stackTrace) {
                      return const Center(
                        child: Text('无法加载图片'),
                      );
                    },
                  )
                : const Center(
                    child: Text("图片选择中"),
                  ),
          )
        ],
      ),
    );
  }
}

 

posted @ 2025-07-25 14:12  深海里的星星i  阅读(86)  评论(0)    收藏  举报