我已经启动了应用程序,并且尝试调用api,并获取json,但对我不起作用
它向我显示此错误 I / flutter(13300):将getter'length'调用为null。 I / flutter(13300):接收者:null I / flutter(13300):尝试致电:长度
模型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'],
);
}
}
服务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;
}
}
屏幕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,
),
),
],
),
),
),
)
],
);
}
}
答案 0 :(得分:0)
我不确定,但是看起来好像是代码中的错误。
class _CategoriesPageState extends State<CategoriesPage> {
MainModel model = MainModel(); <--- this one
应该是:
CategoryListModel model = new CategoryListModel();
答案 1 :(得分:0)
我认为问题在于您没有在dataa
的构造上实例化CategoryListModel
,这意味着它为空(猜测错误,对Dart不太熟悉)。因此,在请求响应中设置数据之前,此行:
temCount: dataa.length,
调用.length
为空。
相反,我建议将dataa
实例化为一个空数组,如下所示:
// ...
Category category = Category();
dataa = [];
// ...