简体   繁体   English

我正在尝试借助颤振中的模型类从 api 加载数据

[英]I am trying to load data from api with the help of model class in flutter

I am trying to fetch data from api and bind with model class at the time of loading data with list im getting null object.我正在尝试从 api 获取数据并在加载数据时与模型类绑定,我正在获取空对象的列表。 i havae tried so many solutions but no one method will work.我尝试了很多解决方案,但没有一种方法行得通。 the code which i have tried from github.我从github尝试过的代码。

class _ChooseRecipientPageState extends State<ChooseRecipient1> {

  void recepinets(){
    receipientModel().then((dynamic res){
      setState(() {
        widget._recepientModel=res;
      });
    });
  }

  //Here i am trying to access data from model class which is load in list type of variable

          Container(
            child: new Flexible(
              child: ListView.builder(
                itemCount:widget._recepientModel.length,
                itemBuilder: (context,index) {
                  return GestureDetector(
                    onTap: () => {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => PostYourStatus(
                          ),
                        ),
                      ),
                    },

//Here i am trying to access data from model class which is load in list type of variable and with the help of this variable i will access its property. //在这里,我试图访问模型类中的数据,该数据以列表类型的变量加载,并在此变量的帮助下访问其属性。

                          Container(
                            width: 230,
                            child: Padding(
                              padding: const EdgeInsets.all(10),
                              child: Column(
                                children: <Widget>[
                                  Row(
                                    children: <Widget>[
                                      Text(
                                        '${widget._recepientModel[index].successData[index].firstName}',
                                        style: TextStyle(
                                            fontFamily: 'Poppins',
                                            fontSize: 17),
                                      ),
                                    ],
                                  ),

// Here its my model class // 这是我的模型类

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';


class RecepientModel {
  String status;
  List<SuccessData> successData;
  int dataCount;

  RecepientModel({this.status, this.successData, this.dataCount});

  RecepientModel.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['success_data'] != null) {
      successData = new List<SuccessData>();
      json['success_data'].forEach((v) {
        successData.add(new SuccessData.fromJson(v));
      });
    }
    dataCount = json['data_count'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    if (this.successData != null) {
      data['success_data'] = this.successData.map((v) => v.toJson()).toList();
    }
    data['data_count'] = this.dataCount;
    return data;
  }
}

class SuccessData {
  int id;
  String firstName;
  String lastName;
  String email;
  String phoneNumber;
  String profileImage;
  String giftedTagLine;

  SuccessData(
      {this.id,
        this.firstName,
        this.lastName,
        this.email,
        this.phoneNumber,
        this.profileImage,
        this.giftedTagLine});

  SuccessData.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    firstName = json['first_name'];
    lastName = json['last_name'];
    email = json['email'];
    phoneNumber = json['phone_number'];
    profileImage = json['profile_image'];
    giftedTagLine = json['gifted_tag_line'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['first_name'] = this.firstName;
    data['last_name'] = this.lastName;
    data['email'] = this.email;
    data['phone_number'] = this.phoneNumber;
    data['profile_image'] = this.profileImage;
    data['gifted_tag_line'] = this.giftedTagLine;
    return data;
  }
}

Future<List<SuccessData>> receipientModel() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var accessToken =prefs.getString("token");
  var id =prefs.getString("id");
  var url = 'https://bruyou.project-demo.info/api/V1/customer/${id}/chooseRecipient';
  //encode Map to JSON
  var response = await http.get(url,headers: {"Content-Type": "application/json","Authorization":accessToken},);
  final responseJson = json.decode(response.body);
  Iterable list=responseJson['successData'];

  if(responseJson['status']==200){
    return list.map((mod) => SuccessData.fromJson(mod)).toList();
  }
}

You are trying to do a setState on StatelessWidget by widget.variable .您正在尝试通过widget.variable在 StatelessWidget 上执行setState You didn't show all widget, but I guess it has some property of _recepientModel which is probably null during Widget render.您没有显示所有小部件,但我猜它具有_recepientModel某些属性,在小部件呈现期间可能为空。 If you want to fetch data on Widget load, you should add _recepientModel state variable in StatefullWidget and inside initState lifecycle function, call api fech and then do a setState wich will rerender the widget with new data.如果您想在 Widget 加载时获取数据,您应该在 StatefullWidget 和initState生命周期函数中添加_recepientModel状态变量,调用 api fech 然后执行 setState 将使用新数据重新渲染小部件。

What's more you should do some kind of assertion that _recepientModel (I'm only guessing is a List) isn't null or has some items inside.更重要的是你应该做某种断言 _recepientModel (我只是猜测是一个列表)不为空或里面有一些项目。 If not, then it won't render inside itemBuilder .如果没有,则它不会在itemBuilderitemBuilder To make it easy you can set _recepientModel state variable as empty list at the beginning.为方便_recepientModel您可以在开始时将_recepientModel状态变量设置为空列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 When I am using the provider package in Flutter to load data from an API into a list it repeatedly calls the API, how do I fix it? - When I am using the provider package in Flutter to load data from an API into a list it repeatedly calls the API, how do I fix it? Flutter:我正在尝试从 Firestore 读取数据中的 URL - Flutter: I am trying to read the URL in the data from the Firestore 将 min SDK 从 2.7.0 更改为 2.12.0 时无法从 API 加载数据。 我究竟做错了什么? (扑) - Unable to load data from API when changing min SDK to 2.12.0 from 2.7.0. what am I doing wrong? (Flutter) 我正在尝试从 API 获取数据但出现错误 - I am trying to get data from API but having error I am trying to fetch collection from shopify admin api with rest api in flutter - I am trying to fetch collection from shopify admin api with rest api in flutter 我在尝试将数据从云 Firestore 带到我的 flutter 应用程序时遇到此错误 - I am getting this error while am trying to bring data from cloud firestore to my flutter app 我正在尝试从 API 中获取 TimeZones,但由于某种原因,它没有返回所有 timeZones - I am trying to get TimeZones from an API in flutter but due to some reason its not returning all timeZones 我正在尝试将数据从我的 flutter 应用程序保存到谷歌表格,但我收到格式异常 - i am trying to save data from my flutter app to google sheets ,but i get a format exception 我正在尝试将 Json 数据转换为 model class 在 ZC047B10EEE71CC268 但我收到“Flutter FormatException:意外字符”错误 - I'm trying to prase the Json data to model class in Flutter. but i'm getting "Flutter FormatException: Unexpected character" Error 我正在尝试使用 https.MultipartRequest 在 Flutter 中调用 API - I am trying to make a call to an API with https.MultipartRequest in Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM