Flutter:在热重新加载之前无法加载资产和path_provider

时间:2020-06-16 18:12:51

标签: image flutter load

我正在从Internet下载图片并将其保存在平台目录中。
我从path_provider和(await getApplicationDocumentsDirectory()).path获取平台的目录。
在iOS上,效果很好,但在Android上,我总是得到Unable to load asset: <path_to_my_directory>

编辑:我第一次启动时遇到此错误,热重启后,它运行得很好...

这是要测试的代码示例:

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  bool dataLoaded = false;
  String pathToSave;

  @override
  void initState() {
    downloadImage();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: dataLoaded ? getImageBody() : CircularProgressIndicator()
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  getImageBody() {
    return Image.asset(pathToSave);
  }

  void downloadImage() async {
    String url = 'https://github.githubassets.com/images/modules/open_graph/github-mark.png';
    pathToSave = '${(await getApplicationDocumentsDirectory()).path}/github-mark.png';
    await Dio().download(url, pathToSave);
    print(pathToSave);
    setState(() {
      dataLoaded = true;
    });
  }
}

依赖项:

path_provider: ^1.6.11
dio: ^3.0.9

1 个答案:

答案 0 :(得分:0)

对于遇到类似问题的所有人:

  • Image.asset(path)加载资产,即在应用开始前的路径 中。
  • Image.file(path)加载资产/文件,只需要引用文件即可,例如文件路径)。也就是说,可以在应用启动前动态添加或静态添加资产。