【问题标题】:How to fix flutter widget flickering?如何修复颤振小部件闪烁?
【发布时间】:2021-04-11 04:42:15
【问题描述】:

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

P.S 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();
        }
      },
    );
  }
}

【问题讨论】:

    标签: android firebase flutter google-cloud-firestore


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 2018-10-18
      • 2020-02-01
      • 1970-01-01
      • 2020-05-30
      • 2011-02-06
      相关资源
      最近更新 更多