首页 > 解决方案 > 颤振显示在 null 上调用了方法“[]”。在列表生成器上

问题描述

我正在从 api 获取数据并在 ListView 构建器中显示但它显示错误

 class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);


  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool show = false;
  var map = {};
  @override
  void initState() {
    dosomestuff();

  }
  Future<List> dosomestuff() async {
    http.Response res = await http.get(
      'http://retailapi.airtechsolutions.pk/api/menu/2112',
    );

    Map<String, dynamic> map = json.decode(res.body);

    if (map['description'] == "Success") {
      print('show kr ');
      print(map["Categories"].length);
      print(map["Categories"]);
      setState(() {
        show = true;
      });
    }
  }



  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: show
          ? ListView.builder(
        itemCount: map["Categories"].length,
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        itemBuilder: (context, index) {
          return Container(
            width: 80.0,
            child: Text(map["Categories"][index]['Name'])
          );
        },
      ) : Container(),

    );
  }
}

它的显示错误The method '[]' was called on null。但是当我在状态函数中打印值时,它的打印值和所有东西都在工作,但是当在 ListBuilder 中显示错误时,它会显示该错误。

你可以看到我打印函数中的值

  print(map["Categories"].length);
  print(map["Categories"]);

它的印刷价值一切都很好。

在此处输入图像描述

您可以在图像中看到它打印的长度和数组很好,所以当我在小部件中使用它说长度被调用时它不为空 -_-

标签: flutter

解决方案


你能试试这个吗?我可能打错了括号。

class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      bool show = false;
      var map = {};
      List<dynamic>  getCategory;

   @override
    void initState() {
     dosomestuff();

      }
 Future<List> dosomestuff() async {
       await http.get(
       'http://retailapi.airtechsolutions.pk/api/menu/2112',
        ).then((result){
       http.Response res=result;
       Map<String, dynamic> map = json.decode(res.body);

       if (map['description'] == "Success") {       
      if(map["Categories"].length>0){
         setState(() {
           show = true;
      getCategory=map["Categories"];
        });
        }
     }
   }

   });






 @override
 Widget build(BuildContext context) {

  return Scaffold(
    appBar: AppBar(

     title: Text(widget.title),
    ),
   body: show
      ? ListView.builder(
    itemCount: getCategory.length,
    scrollDirection: Axis.horizontal,
    shrinkWrap: true,
    physics: BouncingScrollPhysics(),
    itemBuilder: (context, index) {
      return Container(
        width: 80.0,
        child: Text(getCategory[index]['Name'])
      );
    },
    ) : Container(),

    );
   }
 }

推荐阅读