【问题标题】:Flutter default image not loadingFlutter默认图像未加载
【发布时间】:2018-04-29 05:35:32
【问题描述】:

Flutter 新手。从事个人项目。遇到与显示图像相关的小问题。这是我用于显示图像的小部件代码。

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';

class UserProfile extends StatefulWidget {
  @override
  UserProfileState createState() => new UserProfileState();
}

class UserProfileState extends State<UserProfile> {

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  Map userDetails = {};
  String profileImgPath;

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


  Future<Null> getUserDetails() async {
    try {
      final SharedPreferences prefs = await _prefs;
      this.userDetails = json.decode(prefs.getString('user'));

      if (prefs.getString('user') != null) {
        if (this.userDetails['isLoggedIn']) {
          setState(() {
            this.profileImgPath = this.userDetails['profileImg'];
            print('Shared preference userDetailsss : ${this.userDetails}');
          });
        }
      } else {
        print('Shared preference has no data');
      }
    } catch (e) {
      print('Exception caught at getUserDetails method');
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget profileImage = new Container(
      margin: const EdgeInsets.only(top: 20.0),
      child: new Row(
        children: <Widget>[
        new Expanded(
          child: new Column(
            children: <Widget>[
              new CircleAvatar(
                backgroundImage: (this.profileImgPath == null) ? new AssetImage('images/user-avatar.png') : new CachedNetworkImageProvider(this.profileImgPath),
                radius:50.0,
              )
            ],
          )
        )
        ],
      )
    );

    return new Scaffold(
      appBar: new AppBar(title: new Text("Profile"), backgroundColor: const Color(0xFF009688)),
      body: new ListView(
        children: <Widget>[
          profileImage,
        ],
      ),
    );
  } 
}  

我想要做的是,只要CachedNetworkImageProvider 没有得到原始图像,就显示默认的user-avatar.png 图像。但是,它的行为有点不同。

每当我打开页面时,我都会看到一个空白的蓝色框,然后突然出现来自CachedNetworkImageProvider 的原始图像。

无法理解发生了什么。


@Jonah Williams 供您参考 -

【问题讨论】:

    标签: flutter


    【解决方案1】:

    CachedNetworkImage 不能用于backgroundImage 属性,因为它没有扩展ImageProvider。您可以创建一个自定义的CircleAvatar,如下所述以使用CachedNetworkImage 包:

    import 'package:cached_network_image/cached_network_image.dart';
    import 'package:flutter/material.dart';
    
    class CustomCircleAvatar extends StatelessWidget {
    
      final int animationDuration;
      final double radius;
      final String imagePath;
    
      const CustomCircleAvatar({
        Key key, 
        this.animationDuration, 
        this.radius, 
        this.imagePath
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return new AnimatedContainer(
          duration: new Duration(
            milliseconds: animationDuration,
          ),
          constraints: new BoxConstraints(
            minHeight: radius,
            maxHeight: radius,
            minWidth: radius,
            maxWidth: radius,
          ),
          child: new ClipOval(
            child: new CachedNetworkImage(
              errorWidget: (context, url, error) => Icon(Icons.error),
              fit: BoxFit.cover,
              imageUrl: imagePath,
              placeholder: (context, url) => CircularProgressIndicator(),
            ),
          ),
        );
      }
    
    }
    

    以及如何使用:

    body: new Center(
            child: new CustomCircleAvatar(
              animationDuration: 300,
              radius: 100.0,
              imagePath: 'https://avatars-01.gitter.im/g/u/mi6friend4all_twitter?s=128',
            ),
          ),
    

    也许这不是更好的方法。但是,它有效!

    【讨论】:

    • CachedNetworkImage 还提供了一个imageBuilder,您可以使用它来创建自定义图像,从而避免所有这些过程。例如:imageBuilder: (_, imageProvider) =&gt; CircleAvatar( backgroundImage: imageProvider, radius: 20, )
    【解决方案2】:

    (我假设 CachedNetworkImageProvider 实际上是来自 this 包的 CachedNetworkImage)。

    这行代码会一直显示第二张图片。

    (this.profileImgPath == null)
      ? new AssetImage('images/user-avatar.png')
      : new CachedNetworkImageProvider(this.profileImgPath)
    

    由于 profileImagePath 不为 null,因此永远不会创建 AssetImage。即使它是,只要它不是缓存的网络图像,它就会在加载之前替换它。而是使用网络映像的placeholder 参数。这将显示您的资产图像,直到网络图像加载。

    new CachedNetworkImage(
      placeholder: new AssetImage('images/user-avatar.png'),
      imageUrl: profileImgPath,
    )
    

    【讨论】:

    • 感谢您的回复。我也试过CachedNetworkImage()。但是,每当我尝试时,我都会收到此错误The argument type 'CachedNetworkImage' can't be assigned to the parameter type 'ImageProvider.
    • 在帖子底部主要包含错误截图以供参考。
    • 啊我现在明白了,忽略我的回答这是我在深夜做事得到的结果
    • 没问题。下午 6 点后我也会遇到同样的情况:D
    猜你喜欢
    • 2015-08-20
    • 2021-12-25
    • 2020-08-16
    • 2019-10-23
    • 2019-06-29
    • 1970-01-01
    • 2021-05-16
    • 2011-11-24
    • 1970-01-01
    相关资源
    最近更新 更多