外部のファイルを読み込みたい
file_picker
を使うhttps://pub.dev/packages/file_picker
install
pubspec.yaml
に追記
dependencies:
file_picker: ^4.5.1
flutter:
sdk: flutter
pub getする
flutter pub get
main.dartなど、file_pikcerを使うファイルでimportする
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
...
使い方
ファイルパスやメタ情報の取得
ファイルパスやメタ情報のみ必要な場合
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: const MyHomePage(title: 'Flutter Rank Beginner'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Text('top'),
Row(
children: [
Flexible(
child: TextField(),
),
ElevatedButton(
child: Text('Button'),
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles();
if (result != null) {
PlatformFile file = result.files.single;
print(file.path);
} else {
print('User Canceled');
}
},
),
],
),
Text('bottom'),
],
),
);
}
}
選択したテキストファイルの読み込み
ioを使う。
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: const MyHomePage(title: 'Flutter Rank Beginner'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Text('top'),
Row(
children: [
Flexible(
child: TextField(),
),
ElevatedButton(
child: Text('Button'),
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.first.path!);
String filePath = file.path;
print(filePath);
// ファイル全体を文字列として読み込む
String fileData = await file.readAsString();
print(fileData);
// ファイルを1ずつリストとして読み込む
List fileDatas = await file.readAsLines();
fileDatas.forEach((element) {
print(element.toString());
});
} else {
print('User Canceled');
}
},
),
],
),
Text('bottom'),
],
),
);
}
}