一、思考
在Android开发中经常会遇到需要将asset中的文件拷贝到本地目录中,所以Flutter 是否有能够读取 asset 中文件的API呢?rootBundle 就可以解决该问题。
二、代码
flutter: uses-material-design: true assets: - images/lovely_girl.jpg - images/travel_model.json - images/hello.json
import 'dart:convert';import 'dart:developer';import 'dart:io';import 'dart:typed_data';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:path_provider/path_provider.dart';class RootBundlePage extends StatefulWidget { const RootBundlePage({Key? key}) : super(key: key); @override _RootBundlePageState createState() => _RootBundlePageState();}class _RootBundlePageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('RootBundle'),), body: Container( child: Column( children: [ MaterialButton(onPressed:readDataFromBundle, child: Text('读入数据'),), MaterialButton(onPressed:readAndWriteImage, child: Text('读入图片并写入到指定文件'),), ], ), ), ); } void readDataFromBundle() async { String data = await rootBundle.loadString("images/hello.json"); log("readDataFromBundle $data"); var mapData = json.decode(data); Person person = Person.from(mapData); log("${person.name}"); } void readAndWriteImage() async { String fileName = "lovely_girl.jpg"; var bytes = await rootBundle.load("images/lovely_girl.jpg"); String dir = (await getApplicationSupportDirectory()).path; String filePath = "$dir/$fileName"; ByteBuffer buffer = bytes.buffer; File file = await new File(filePath).writeAsBytes(buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes)); log("readAndWriteImage ${file.path}"); //[log] readAndWriteImage /data/user/0/com.example.flutter_widgets/files/lovely_girl.jpg // /data/data/com.example.flutter_widgets/files/lovely_girl.jpg }}//{"name": "lisi", "age": 20, "address": "beijing", "gender":"male"}class Person{ String? name; int? age; String? address; String? gender; Person(this.name, this.age, this.address, this.gender); Person.from(Map json){ this.name = json['name']; this.age = json['age']; this.address = json['address']; this.gender = json['gender']; } Map toJson(){ Map data = new Map(); data['name'] = this.name; data['age'] = this.age; data['address'] = this.address; data['gender'] = this.gender; return data; }}
参考:
Flutter读取assets文件并写入应用程序路径 - 简书