dart LateInitializationError:字段“data”尚未初始化,出现错误

n9vozmp4  于 2023-05-04  发布在  其他
关注(0)|答案(4)|浏览(204)

有没有在此代码中的错误,但这个错误是在运行后,有人可以请提供一个示例代码需要什么来解决下面的错误?“LateInitializationError:字段“data”尚未初始化,出现错误
这是我的主页. dart。

import 'package:fi_digital_earn/DashBoards/PromoCode/provider/myHomePageProvider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          ChangeNotifierProvider<MyHomePageProvider>(
            create: (context) => MyHomePageProvider(),
            child: Consumer<MyHomePageProvider>(
              builder: (context, provider, child) {
                if (provider.data == null) {
                  // print("prov $provider.data");
                  provider.getData(context);
                  return Center(child: CircularProgressIndicator());
                }
                // when we have the json loaded... let's put the data into a data table widget
                return SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  // Data table widget in not scrollable so we have to wrap it in a scroll view when we have a large data set..
                  child: SingleChildScrollView(
                    child: DataTable(
                      columns: [
                        // DataColumn(
                        // label: Text('Verified'),
                        // tooltip: 'represents if user is verified.'),
                        DataColumn(
                            label: Text('Pin ID'),
                            tooltip: 'represents first pin id of the user'),
                        DataColumn(
                            label: Text('Pin Name'),
                            tooltip: 'represents pin name of the user'),
                        DataColumn(
                            label: Text('Used/Unused'),
                            tooltip: 'represents Used/Unused of the user'),
                        DataColumn(
                            label: Text('Date'),
                            tooltip: 'represents date of the user'),
                      ],
                      rows: provider.data.results
                          .map((data) =>
                              // we return a DataRow every time
                              DataRow(
                                  // List<DataCell> cells is required in every row
                                  cells: [
                                    // DataCell((data.verified)
                                    //     ? Icon(
                                    //         Icons.verified_user,
                                    //         color: Colors.green,
                                    //       )
                                    //     : Icon(Icons.cancel, color: Colors.red)),
                                    // I want to display a green color icon when user is verified and red when unverified
                                    DataCell(Text(data.pin_id)),
                                    DataCell(Text(data.pin_name)),
                                    DataCell(
                                      RaisedButton(
                                          onPressed: () {},
                                          color: data.used_pin == "1"
                                              ? Colors.green
                                              : Colors.red,
                                          shape: new RoundedRectangleBorder(
                                            borderRadius:
                                                new BorderRadius.circular(30.0),
                                          ),
                                          // shape: Border.all(
                                          //   color: Colors.purple,
                                          //   width: 2.0,
                                          // ),
                                          // splashColor: Colors.cyan,
                                          // highlightColor: Colors.blue,
                                          child: data.used_pin == "1"
                                              ? Text("Useed")
                                              : Text("Unused")),
                                    ),

                                    DataCell(Text(data.pin_date)),
                                  ]))
                          .toList(),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

这是我的供应商。

import 'dart:convert';
import 'package:fi_digital_earn/DashBoards/PromoCode/model/myData.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
class MyHomePageProvider extends ChangeNotifier {
  late MyData data;

  Future getData(context) async {
   
    var url = Uri.parse(
        'https://software.oceonicitsolution.com/hrms/v3/mlm_api/v1/PromoCodeApi.php');
    var response = await http.get(url);
    print("res${response.body}");
    // now we have response as String from local json or and API request...
    var mJson = json.decode(response.body);
    // print("mjson" + mJson);
    this.data = MyData.fromJson(mJson);
    // this.data = http.post(mJson) as MyData;
    this.notifyListeners(); // for callback to view
  }
}

这是我的模特角色

class MyData {
  List<Results> results = [];

  MyData.fromJson(Map<String, dynamic> json) {
    // previous = json['previous'];
    // next = json['next'];
    if (json['results'] != null) {
      results = <Results>[];
      json['results'].forEach((v) {
        results.add(new Results.fromJson(v));
      });
    }
  }
}

class Results {
  String pin_id = "";
  String pin_name = "";
  String used_pin = "";
  String pin_date = "";

  Results.fromJson(Map<String, dynamic> json) {
    pin_id = json['pin_id'];
    pin_name = json['pin_name'];
    used_pin = json['use_unuse'];
    pin_date = json['pin_date'];
  }
}
up9lanfz

up9lanfz1#

你不需要一个late变量,你需要一个可以为空的变量。如果你需要检查某个东西是否被初始化,你应该使用一个可空的变量,并且你的代码已经设置好检查null
换衣服就行了

late MyData data;

MyData? data;
vmjh9lq9

vmjh9lq92#

您可以将其更改为:

MyData data = MyData(); //by initializing it.
//or by making it nullable.
MyData? data;
iyr7buue

iyr7buue3#

当我尝试比较if语句中的延迟值时,我遇到了这个问题。我是如何解决的,我在陈述之前给了一些不重要的值。问题已经解决了。

mccptt67

mccptt674#

我在使用Google Maps API时遇到了同样的问题,解决方案是在AndroidManifest.xml中提供正确的权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

相关问题