微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

    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),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,color: Colors.grey,],);
      }

      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。

pacakge:cached_network_image

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。