0

I've flutter app and I'm trying to calling api, and get json but It doesn't work with me

It shows to me this error I/flutter (13300): The getter 'length' was called on null. I/flutter (13300): Receiver: null I/flutter (13300): Tried calling: length

Model Category_list.dart

class Category {
  List<Data> data;
  String status;
   Category({this.data, this.status});

  factory Category.fromJson(Map<String, dynamic> json) {
    var list1=json['data'] as List;
    List<Data> data= list1.map((i)=> Data.fromJson(i)).toList();
    return Category(
      data: data,
      status: json['status']
    );
  }
}

class Data {
  int id;
  String name;
  String image;
  String items;

  Data({this.id, this.name, this.image, this.items});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      id: json['id'],
      name: json['name'],
      image: json['image'],
      items: json['items'],
    );
  }
}

Services Category_list_services.dart

import 'dart:convert';
import 'package:scoped_model/scoped_model.dart';
import 'dart:async' as future;
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Models/Category_list.dart';

class CategoryListModel extends Model {
  bool _CategoryLoading = false;
  Category _category;

  bool get CategoryLoading => _CategoryLoading;

  Dio dio = Dio();

  Future<Response<dynamic>> getCategory() async {
    _CategoryLoading = true;
    notifyListeners();
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    dio.options.headers = {'lang': 'en', 'Authorization': prefs.get('token')};
    dio.options.baseUrl = "I put here my api url";

    return await dio.get('/category/list');
  }

  Future<Category> loadCategoryResponse() async {
    var jsonString, jsonResponse;
    try {
      jsonString = await getCategory();

      jsonResponse = json.decode(jsonString.toString());
      print(jsonResponse);
      _category = Category.fromJson(jsonResponse);
      if (jsonString.statusCode >= 200 && jsonString.statusCode < 300) {
       _CategoryLoading = true;
        notifyListeners();
        return _category;
      } else {
        throw Exception("atefffffffffffffffff");
//        _CategoryLoading = false;
//        notifyListeners();
//
//        return _category;
      }
    } on DioError catch (e) {
      if (e.response != null) {
        _CategoryLoading = false;
        notifyListeners();
      }
    }

    return _category;
  }
}

Screen CategoriesPage.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../Models/Category_list.dart';
import '../Scoped_model/main_model.dart';

class CategoriesPage extends StatefulWidget {
  @override
  _CategoriesPageState createState() => _CategoriesPageState();
}

class _CategoriesPageState extends State<CategoriesPage> {
  MainModel model = MainModel();
  Category category = Category();
  var dataa;
  @override
  void initState() {
    model.loadCategoryResponse().then((data){
      setState(() {
         this.dataa= data;

      });
    }

    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        backgroundColor: Theme.of(context).primaryColor,
        appBar: AppBar(
          backgroundColor: Theme.of(context).accentColor,
          elevation: 0.0,
          title: Text(
            " الاقسام",
            style: TextStyle(
              color: Colors.white,
            ),
          ),
          centerTitle: true,
          leading: Icon(
            Icons.search,
            color: Colors.white,
          ),
        ),
        endDrawer: Drawer(
          child: Container(
            color: Theme.of(context).accentColor,
            child: Directionality(
              textDirection: TextDirection.rtl,
              child: Center(
                child: ListView(
                  children: <Widget>[
                    SizedBox(
                      height: 100,
                    ),
                    //------------------home----------
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed("/homepage");
                      },
                      title: Text(
                        "الصفحة الرئيسية",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.home,
                        color: Colors.white,
                      ),
                    ),
                    //------------------latest--------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed("/latest");
                      },
                      title: Text(
                        "الاخيرة",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.view_list,
                        color: Colors.white,
                      ),
                    ),
                    //--------------------Popular---------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed("/popular");
                      },
                      title: Text(
                        "شائع",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.local_florist,
                        color: Colors.white,
                      ),
                    ),
                    //--------------rated------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed("/rated");
                      },
                      title: Text(
                        "تقيم",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.group,
                        color: Colors.white,
                      ),
                    ),
                    //-----------------categories--------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      title: Text(
                        "الاقسام",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.folder_open,
                        color: Colors.white,
                      ),
                    ),

//---------------------Gifs-------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed("/Gif");
                      },
                      title: Text(
                        "شائع",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.gif,
                        color: Colors.white,
                      ),
                    ),
                    //----------------favourite-------------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed('/favourite');
                      },
                      title: Text(
                        "المفضلة",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.favorite_border,
                        color: Colors.white,
                      ),
                    ),
                    //--------------profile---------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed('/profile');
                      },
                      title: Text(
                        "الصفحة الشخصية",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.person_pin_circle,
                        color: Colors.white,
                      ),
                    ),
                    //---------------settings-------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {},
                      title: Text(
                        "الاعدادات",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.settings,
                        color: Colors.white,
                      ),
                    ),
                    //-----------------login--------------
                    SizedBox(
                      height: 7,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).pushNamed("/singin");
                      },
                      title: Text(
                        "تسجيل خروج",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      leading: Icon(
                        Icons.settings_backup_restore,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        body: GridView.builder(
            shrinkWrap: true,
            scrollDirection: Axis.vertical,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3, crossAxisSpacing: 3, mainAxisSpacing: 3),
           itemCount: dataa.length,
            itemBuilder: (BuildContext context,int index) {
              return gridItem(dataa[index].name,
                  dataa[index].image,dataa[index].items);
            }));
  }

  Widget gridItem(String text, String photo, String item) {
    return Stack(
      children: <Widget>[
        Container(
          height: 150,
          width: 150,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(60),
              image:
                  DecorationImage(image: AssetImage(photo), fit: BoxFit.cover),
              color: Colors.red),
          child: Align(
            alignment: Alignment.center,
            child: Padding(
              padding: const EdgeInsets.only(top: 25),
              child: Column(
                children: <Widget>[
                  Text(
                    text,
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                  Text(
                    item,
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
        )
      ],
    );
  }
}
Maichale
  • 29
  • 1
  • 3
  • 6

2 Answers2

1

I'm uncertain but it looks like a mistake in the code.

class _CategoriesPageState extends State<CategoriesPage> {
  MainModel model = MainModel(); <--- this one

It should be:

CategoryListModel model = new CategoryListModel();
Pete Houston
  • 14,931
  • 6
  • 47
  • 60
0

I believe the problem is that you're not instantiating dataa on construction of the CategoryListModel, which means it's null (guessing by the error, not too familiar with Dart). So before the dataa gets set in the request response, this line:

temCount: dataa.length,

is calling .length on null.

Instead, I recommend instantiating dataa as an empty array, something like this:

// ...
Category category = Category();
dataa = [];
// ...
DevK
  • 9,597
  • 2
  • 26
  • 48