【问题标题】:The Method [] was called on null方法 [] 在 null 上被调用
【发布时间】:2021-02-26 02:05:55
【问题描述】:

我是 Flutter 的新手。我在 YouTube 和 Google 上看到了很多教程,但我找不到解决方案。我该如何解决这个错误?

import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:convert';
import 'data/shelfscreendata.dart';
import 'package:google_fonts/google_fonts.dart';
import 'constant/constant.dart' as Constants;
import 'PhotographerWelcomeNote.dart';
import 'package:http/http.dart' as http;
import 'Utility/global.dart' as Globals;
import 'data/errordata.dart';
import 'data/shelfscreendata.dart';
import 'data/shelfscreendata.dart';



class ShelfScreen extends StatefulWidget {
@override
_ShelfScreenState createState() => _ShelfScreenState();
}

class _ShelfScreenState extends State<ShelfScreen> {
bool  _isLoading = false;
Map CompaignShelfList;
List CampiagnData;

Future Shelf() async {
   Map data = {
  "AccessToken": "MjUyLTg1REEyUzMtQURTUzVELUVJNUI0QTIyMTE=",
  "CustomerId": 1
 };

 final http.Response response = await http.post(
   "http://api.pgapp.in/v1/shelflist",
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
  body: jsonEncode(data),
   );
   var jsonResponse = null;
   CompaignShelfList = json.decode(response.body);
   setState(() {
     CampiagnData = CompaignShelfList["CompaignShelfList"];
   });
   //       debugPrint(CompaignShelfList.toString());
   if (response.statusCode == 200)
   {
     jsonResponse = json.decode(response.body);
     print("Response status : ${response.statusCode}");
     print("Response status : ${response.body}");
     if(jsonResponse != null && ! jsonResponse.containsKey("Error")){
       setState(() {
         _isLoading = false;
       });
     }
     else{
       setState(() {
         _isLoading = false;
       });
       print("Response status : ${response.body}");
     }
   }
   }
  @override
 void initState() {
 super.initState();
 Shelf();
  }
 @override
 Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    backgroundColor: const Color(0xfff8f8f8),
    leading: Padding(
      padding: EdgeInsets.only(left: 20),
      child:  Image.asset("assets/logo.png",width: 45,height: 45,),
    ),
    title: Center(
      child: Image.asset("assets/Textimage.png",width: 170,height: 45),
    ),
    actions: <Widget>[
         Padding(
           padding: const EdgeInsets.only(right: 20,top: 10,bottom: 10),
           child: Container(
            height: 8,
            width: 35,
            child: CircleAvatar(
              maxRadius: 20,
              backgroundImage: AssetImage("assets/images/prof.jpg"),
            ),
        ),
         ),

    ],

  ),
  body: GridView.builder(
      shrinkWrap: false,
      scrollDirection: Axis.vertical,
      gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 1.200,
        mainAxisSpacing: 1.0,
        crossAxisSpacing: 1.0,

      ),
      itemCount: CompaignShelfList.length,
      itemBuilder: (context, int index){
        return 
          CategoriesTile(
          imgUrls: CompaignShelfList[index]["CoverImagePath"],
          catagory:CompaignShelfList[index]["CampaignTitle"],
          date: CompaignShelfList[index]["Date"],
          email: CompaignShelfList[index]["PhotographerEmail"],
          stduio:CompaignShelfList[index]["BusinessName"],
        );
   //              Image.asset(Shelflist[index]["text_3"],fit: BoxFit.cover,);
      }
  )

  );

 }
 }




 class CategoriesTile extends StatelessWidget {
final String imgUrls, catagory , date,email,stduio;

 CategoriesTile({@required this.imgUrls, @required this.catagory,@required this.date,@required 
this.email,@required this.stduio});

@override
Widget build(BuildContext context) {
return GestureDetector(
  onTap: () {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PhotographerWelcomeNote(
              Coverpic: imgUrls,
            )));
  },
  child: Card(
    semanticContainer: true,
    clipBehavior: Clip.antiAliasWithSaveLayer,
    elevation: 5,
    child: Container(
      margin: EdgeInsets.all(8),
      child:
            Stack(
        children: <Widget>[
          Positioned(
            top: 1,
            left: 1,
            right: 1,
            bottom: 50,
            child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child:Image.asset(
                  imgUrls,
                  height: 250,
                  width: 400,
                  fit: BoxFit.cover,
                )
               ),
          ),
          Positioned(
            bottom: 50,
            left: 1,
            right: 1,
       //                width: 400,
            height: 60,
            child: ClipRect(
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3),
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0),
                    borderRadius: BorderRadius.circular(8),
                  ),

                ),
              ),
            ),
          ),
         Positioned(
           bottom: 80,
           left: 20,
           child: Container(
                  height: 50,
                  width: 400,
                  alignment: Alignment.bottomLeft,
                  child: Text(
                    catagory ?? "Yo Yo",
                    style: GoogleFonts.nunito(
                      fontSize: 18,
                      color: const Color(0xffffffff),
                      fontWeight: FontWeight.w700,
                      height: 1.7647058823529411,
                    ),
                  )),
         ),
          Positioned(
            left: 20,
            bottom: 60,
            child: Container(
                   height: 30,
                   width: 150,
                alignment: Alignment.bottomLeft,
                          child: Text(
                    date,style: GoogleFonts.nunito(
                  fontSize: 13,
                  color: const Color(0xffffffff),
                  fontWeight: FontWeight.w700,
                  height: 1.7647058823529411,
                ),
                ),
              ),
          ),
                     Positioned(
                   bottom: 20,
                       left: 90,
                       child: Container(
                       height: 23,

                       alignment: Alignment.center,
                         child: Text(
                         stduio,
                             style: GoogleFonts.nunito(
                           fontSize: 18,
                         color: const Color(0xff7f7f7f),
                         fontWeight: FontWeight.w700,
                         )
                       ),
                     ),
                     ),
                      Positioned(
                               bottom: 1,
                                left: 90,
                           child: Container(
                                  height: 20,

                            alignment: Alignment.center,
                            child: Text(
                              email,style: GoogleFonts.nunito(
                              fontSize: 10,
                              color: const Color(0xffb4b4b4),
                              fontWeight: FontWeight.w600,
                            ),
                            ),
                           ),
                      ),
          Positioned(
           bottom: 2,
            left: 10,
            child: Container(
              width: 66.0,
              height: 39.0,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: const AssetImage(
                      'assets/images/camlogo.jpg'),
                  fit: BoxFit.cover,
                ),
                border: Border.all(
                    width: 1.0, color: const Color(0xffb4b4b4)),
              ),
            ),
          ),
        ],
      ),
    ),
  ),

 );
 }
 }

【问题讨论】:

  • 调试正在查看有错误的控制台,查看堆栈跟踪,99% 的时间错误会告诉您在哪一行上哪个字符上抛出了错误以及究竟是什么错误,它会告诉你应该做什么,而且对我们来说会更容易。
  • 您好,我有两个建议。 1. 您能否确认您确实从 API 调用中获取了一些数据?如果您可以提供带有堆栈的错误消息,那将非常有帮助。 2. 你不应该把你的代码和敏感数据放在一起,比如AccessToken 这里。只需用* 掩盖它,或者发表评论或除实际令牌值之外的任何其他内容:)
  • 您的 API 似乎已损坏。我没有得到答案。这可能是您的响应正文无法转换为 Json 的问题。
  • 看起来有人在做the same error here - 同样的作业?

标签: json flutter


【解决方案1】:

如果调用方法的变量尚未初始化,通常会抛出错误x was called on null。您可能想查看CompaignShelfList = json.decode(response.body); 并查看它是否有可以在使用CompaignShelfList["CompaignShelfList"] 使用键从映射中获取值之前解码的响应

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 2021-11-30
    • 2020-11-10
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2019-02-07
    • 2020-04-09
    相关资源
    最近更新 更多