Flutter - 使用 laravel 获取方法 api

Posted

技术标签:

【中文标题】Flutter - 使用 laravel 获取方法 api【英文标题】:Flutter - Get method api with laravel 【发布时间】:2019-11-07 20:26:36 【问题描述】:

我有颤振的应用程序,我正在尝试调用 api,并获取 json,但它不适用于我

它向我显示了这个错误 I/flutter (13300):在 null 上调用了 getter 'length'。 I/颤振(13300):接收器:空 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;
  


屏幕分类页面.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,
                    ),
                  ),
                ],
              ),
            ),
          ),
        )
      ],
    );
  

【问题讨论】:

【参考方案1】:

我不确定,但它看起来像是代码中的错误。

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

应该是:

CategoryListModel model = new CategoryListModel();

【讨论】:

不,Dart 2 doesn't require new 我不是在谈论 new 关键字。 OP 正在实例化错误的类。【参考方案2】:

我认为问题在于您没有在构造 CategoryListModel 时实例化 dataa,这意味着它为空(根据错误猜测,对 Dart 不太熟悉)。所以在请求响应中设置 dataa 之前,这一行:

temCount: dataa.length,

在 null 上调用 .length

相反,我建议将dataa 实例化为一个空数组,如下所示:

// ...
Category category = Category();
dataa = [];
// ...

【讨论】:

以上是关于Flutter - 使用 laravel 获取方法 api的主要内容,如果未能解决你的问题,请参考以下文章

让 laravel、vuejs 和 Flutter 协同工作的最佳方式是啥?

Laravel API 推送通知到 Flutter

Flutter NoSuchMethodError:在 null 上调用了方法“[]”。使用flutter获取api时如何解决此错误

Api Request 使用 Http 请求获取 get 方法。但不知道 Flutter 中的实际问题

WebSocketChannelException: HandshakeException - Flutter 应用程序与自定义服务器上的 Laravel Websockets 使用 Cpanel 验

Flutter-使用提供程序在init上获取数据的最佳方法