【问题标题】:Flutter 2 second shows error when page load and ater 2 secons successfully shows页面加载时 Flutter 2 秒显示错误,2 秒后成功显示
【发布时间】:2020-12-30 10:26:22
【问题描述】:

您好,这里有 Flutter 专家吗?请帮助meee ...当用户滑动图像并检查我想要在我的代码中是否相同时,我想做的是像Facebook照片查看器一样... 我制作了我的代码,因为我来自列表页面,当我点击列表时,我可以看到全屏图像..并且我可以滑动(滚动)图像... BUTTT 当我第一次出现在这个屏幕上时,它会在屏幕上显示一些错误 3,4 秒......之后我可以看到图像请帮助我并显示我的错误

Future<PhotoDetail> pagedetail() async {
sharedPreferences = await SharedPreferences.getInstance();
Map data = {
"AccessToken": sharedPreferences.getString("AccessToken"),
"CustomerId":  sharedPreferences.getInt("CustomerId"),
"ImageId":   indexx == null ? widget.images[widget.currentindex].photoId : indexx
 };
 print(data);
 final http.Response response = await http.post(
 Constants.CUSTOMER_WEBSERVICE_URL + "/photo/detail",
 headers: <String, String>{
  'Content-Type': 'application/json; charset=UTF-8',
  },
  body: jsonEncode(data),
   );
   var jsonResponse = json.decode(response.body);
   if (response.statusCode == 200) {

    print("Response status : ${response.statusCode}");
    print("Response status : ${response.body}");

    isLike = jsonResponse["IsLike"]; //here i saving value when api is run
    print("iSLiked Value:" +isLike.toString());  // value is printing here
    return PhotoDetail.fromJson(json.decode(response.body));

    } else {

    throw Exception('Failed to load data');
     }
    }

  Future<PhotoDetail> _photoDetail;


 @override
 void initState() {
_photoDetail = pagedetail();
 setState(() {
pagedetail(); //here is my api run when page is load
 });
 super.initState();

 }


 void pageChange(int index){  //this method is when i scroll page 
 setState(() {
  pagedetail();  // api is call again and again
   
  });
  }


@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
body: Stack(
  children: <Widget>[
    Container(
        child:
        Center(
            child: PhotoViewGallery.builder(
              itemCount: widget.images.length,
              builder: (BuildContext context , int index) {
                return PhotoViewGalleryPageOptions(
                  imageProvider:
                  NetworkImage(widget.images[index].photoPreviewImagePath),
                  maxScale: PhotoViewComputedScale.covered * 1.8,
                  minScale: PhotoViewComputedScale.contained * 1.0,
                );
              },
              pageController:  _pageController,
              enableRotation: false,
              scrollDirection: Axis.horizontal,
              onPageChanged: pageChange,
              loadingBuilder: (BuildContext context , ImageChunkEvent event){
                return Center(child: CircularProgressIndicator(),);
              },
            )
        )
    ),

        Positioned(
        bottom: 10,
        left: 30,
        right: 30,
        child: (_photoDetail == null) ? Text("error")
        : FutureBuilder<PhotoDetail>(
          future: _photoDetail,
          // ignore: missing_return
          builder: (context , snapshot){
            int like = snapshot.data.isLike;
            int Slection = snapshot.data.selectedCount;
            print("like ?????:" +like.toString());
            print("Selection ????? :" + Slection.toString());
            if (snapshot.hasData){
              return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    InkWell(
                      child: InkWell(
                          Likes();
                          Fluttertoast.showToast(
                              msg: "Liked",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Color(0xfff58634),
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                        },
                        child:  Icon(Icons.thumb_up,size: 20,color: like == 1 ? Color(0xfff58634) : Colors.white),
                      ),
                    ),
                    InkWell(

                      child:  Icon(Icons.comment,size: 20,color: Colors.white),
                    ),
                    InkWell(
                      onTap: (){
                        _onShare();
                      },
                      child: Icon(Icons.share,size: 20,color: Colors.white,),
                    ),
                    InkWell(
                      onTap: (){},
                      child:  Icon(Icons.photo_album,size: 20,color: Slection == 0 ? Colors.white : Color(0xfff58634)),
                    ),

                    InkWell(
                      onTap: (){
                        setState(() {
                          viewwholike();
                        });
                      },
                      child:  Icon(Icons.card_giftcard,size: 20,color: 
         Colors.white,),
                    ),
                  ]
              );
            }
            else {
              Text("error");
            }
          },
        ),
      ),

  ],
),
);
}
   ERROR::════════ Exception caught by widgets library 
  ═══════════════════════════════════════════════════════
   The following NoSuchMethodError was thrown building 
   FutureBuilder<PhotoDetail>(dirty, state: 
  _FutureBuilderState<PhotoDetail>#ef81b):
  The getter 'isLike' was called on null.
  Receiver: null
  Tried calling: isLike

  The relevant error-causing widget was: 
   FutureBuilder<PhotoDetail>  
  file:///C:/Users/Hello%20Devloper/AndroidStudioProjects/
   September/PhotoGranth- 
    App/lib/CampaignSinglePhotos.dart:400:15
   When the exception was thrown, this was the stack: 
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
     #1      _CampaignSinglePhotosState.build.<anonymous closure> 
     (package:photogranth2020/CampaignSinglePhotos.dart:404:42)
     #2      _FutureBuilderState.build 
     (package:flutter/src/widgets/async.dart:732:55)
     #3      StatefulElement.build 
    (package:flutter/src/widgets/framework.dart:4619:28)
    #4      ComponentElement.performRebuild 
      (package:flutter/src/widgets/framework.dart:4502:15)

【问题讨论】:

    标签: image flutter sliding


    【解决方案1】:

    Flutter 在你测试 snapshot.data.isLike 时告诉你数据还没有准备好。 如果 snapshot.hasData,你应该总是在开始时测试,只有在那之后你才能做你想要的。 否则,如果 snapshot.hasData 为 false,则直接返回 CircularProgressIndicator() 。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 2018-11-08
      相关资源
      最近更新 更多