使用 Flutter,如何在离线时显示本地存储中的 NetworkImage

Using Flutter, how to display a NetworkImage from local storage when OFFLINE

我正在使用 Flutter 开发平板电脑应用程序,我有一个小部件可以在圆形装饰中显示用户头像。为此,我使用网络图像来显示从服务器接收到的图像。但是,存在离线模式的情况。为此,我使用 path_provider 包将用户信息和头像作为 png 文件存储在外部存储中。用户可以看到他的信息,但到目前为止我找不到在这个圆形装饰中显示头像的方法。如果有人可以帮助我,我将不胜感激。以下是我的 Widgets 状态代码,您可以在 build 函数的第一个 else 案例中找到我的试用和注释代码:

    class _UserCardState extends State<UserCard> {
      int id;
      String title;
      String name;
      String surname;
      String password;
      String imageDIR;
    
      var img;
    
      @override
      void initState() {
        this.id = widget.id;
        this.title = widget.title;
        this.name = widget.name;
        this.surname = widget.surname;
        this.password = widget.password;
        this.imageDIR = widget.imageDIR;
        super.initState();
      }
    
      //This is unnecessary
      @override
      void didUpdateWidget(UserCard oldWidget) {
        super.didUpdateWidget(oldWidget);
      }
    
      @override
      Widget build(BuildContext context) {
    
        if(!vars.loadFromTabletStorage) {
          saveImage();
          img = NetworkImage(vars.globalURL + 'api/getUserAvatar/' + id.toString());
        }
        /*else {
          Future<FileImage> imageData = getLocalImage();
          img = imageData;//Image.file(File(imageData.toString()), width: vars.userPictureWidth, height: vars.userPictureHeigth);
        }*/
        print('CONNECTION STATUS ::: ' + (img == null).toString());
    
        //Example: '\nDAVID R.\n'
        String formattedNameSurname = '\n' +
            this.name.toUpperCase() +
            ' ' +
            this.surname.toString().substring(0, 1).toUpperCase() +
            '.\n';
    
        double imageWidth = (this.imageDIR.contains('WorkerSmall.png'))
            ? vars.userDefaultWorkerPictureWidth
            : vars.userPictureWidth;
    
        return Expanded(
          child: Container(
            color: vars.defaultBackgroundColor,
            width: vars.userContainerWidth,
            height: vars.userContainerHeigth,
            child: Column(
              children: <Widget>[
                Material(
                  color: Color.fromARGB(255, 246, 246, 246),
                  child: InkWell(
                    
                    child: CircleAvatar(
                      radius: imageWidth + 3,
                      backgroundColor: Colors.grey, //Color(0xFFFDCF09),
                      child: CircleAvatar(
                        radius: imageWidth,
                        backgroundImage: img,
                      ),
                    ),
                  ),
                ),
                Text(
                  formattedNameSurname,
                  style: new TextStyle(
                    fontSize: 14.0,
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  title.toUpperCase() /*+'\n\n\n'*/,
                  textAlign: TextAlign.center,
                  style: new TextStyle(
                    fontSize: 14.0,
                    color: Colors.grey,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        );
      }

      Future<Uint8List> _readLocallyImageFile() async {
        // Retrieve "External Storage Directory" for Android and "NSApplicationSupportDirectory" for iOS
        Directory directory = Platform.isAndroid
            ? await getExternalStorageDirectory()
            : await getApplicationSupportDirectory();
    
        print('>>>>>>>>>>>> ' + directory.path);
        // Create a new file. You can create any kind of file like txt, doc , json etc.
        File file =
        await File('${directory.path}/' + (id-1).toString() + '.png').create();
    
        // Read the file content
        Uint8List fileContent = await file.readAsBytes();
        print("AVATAR FILE CONTENTS:\n$fileContent\n========================================");
        return fileContent;
      }
    
      Future<FileImage> getLocalImage() async{
        Directory directory = Platform.isAndroid
            ? await getExternalStorageDirectory()
            : await getApplicationSupportDirectory();
    
        File file =
        await File("${directory.path}/" + id.toString() + '.png').create();
        return FileImage(file);
      }
    
      Future<void> saveImage() async {
        // Retrieve "External Storage Directory" for Android and "NSApplicationSupportDirectory" for iOS
        Directory directory = Platform.isAndroid
            ? await getExternalStorageDirectory()
            : await getApplicationSupportDirectory();
    
        var response =
            await http.get(vars.globalURL + 'api/getUserAvatar/' + id.toString());
        print(response.toString());
        File file =
            await File("${directory.path}/" + id.toString() + '.png').create();
        file.writeAsBytesSync(response.bodyBytes);
      }
    }

您可以为此使用 CachedNetworkImage。

包裹:cached_network_image