2

我正在尝试将图像从 firebase 存储加载到我的应用程序,但是我遇到了一个奇怪的问题,即个人资料页面(加载此图像的位置)一直闪烁。图像加载正常,但整个小部件不断闪烁。经过一些调试后,我已将问题缩小到函数 getProfilePic() 中调用的 setState() ,但是我不知道它是函数本身还是我对所述函数的调用。

PS fileURL 或 picRef.getDownloadURL() 没有问题,因为我也使用随机互联网图像对此进行了测试,并且得到了相同的闪烁。

class profileTab extends StatefulWidget {
  @override
  _profileTabState createState() => _profileTabState();
}

class _profileTabState extends State<profileTab> {

  User user = FirebaseAuth.instance.currentUser;
  String _image = "https://picsum.photos/250?image=9";

  Reference picRef = FirebaseStorage.instance.ref().child(FirebaseAuth.instance.currentUser.uid);

  Future<Widget> getProfilePic() async {
    await picRef.getDownloadURL().then((fileURL){
       setState(() {
         _image = fileURL;
       });
    });
  }

  @override
  Widget build(BuildContext context) {
    getProfilePic();
    return StreamBuilder(
      stream: FirebaseFirestore.instance.collection('users').doc(user.uid).snapshots(),
      builder: (context, snapshot){
        if (snapshot.connectionState == ConnectionState.active){
          return ListView(
              children: <Widget>[
                SizedBox(height: 100.0,),
                CircleAvatar(
                  radius: 100.0,
                  backgroundColor: Colors.lightBlueAccent,
                  child: ClipOval(
                    child: SizedBox(
                      width: 180.0,
                      height: 180.0,
                      child: Image.network(_image,fit: BoxFit.fill,),
                    ),
                  ),
                ),
                SizedBox(height: 30.0,),
                Center(child: Text("Name: " + snapshot.data.data()['name'],textScaleFactor: 3.0,)),
              ]
          );
        }
        else {
          return CircularProgressIndicator();
        }
      },
    );
  }
}
4

1 回答 1

2

getProfilePic 正在通过调用 setState 重绘小部件。setState 调用调用 getProfilePic 的 build 方法。

因此,当第一次调用 build 方法时,我们调用 getProfilePic 再次更新小部件树。修复:如果 _image 为 null,则在 getProfilePic 中添加检查以调用 setState,这将仅重绘一次小部件。如果你使用 Image.network 会更好。你可以参考这个 https://www.woolha.com/tutorials/flutter-display-image-from-network-url-show-loading

于 2021-01-05T12:58:15.150 回答