简体   繁体   English

如何解决“用于空值的空检查运算符”-错误?

[英]How to solve "Null check operator used on a null value"-error?

I want to add data from database on List<String> _names = [];我想从数据库中添加数据List<String> _names = []; element.元素。 so for that, I add my API response data to that list but when I tried to initialize that widget which stores the List item it gave an error of Null check operator used on a null value and I don't know what type of error is this I tried much time to resolve it but I can't.因此,为此,我将我的 API 响应数据添加到该列表中,但是当我尝试初始化存储列表项的小部件时,它给出了Null check operator used on a null value的错误,我不知道什么类型的错误是这我尝试了很多时间来解决它,但我不能。 I have a widget that stores the list of names and when I tried to add names on the empty list by Json response so I printed that list and it shows me the actual data which I want but when I initialize the widget it gave me an unnecessary error.我有一个存储名称列表的小部件,当我尝试通过 Json 响应在空列表中添加名称时,我打印了该列表并显示了我想要的实际数据,但是当我初始化小部件时,它给了我一个不必要的错误。

Here is my code:这是我的代码:

  import 'package:mindmatch/screens/Swipers.dart';
  import 'package:flutter/material.dart';
  import 'package:swipe_cards/draggable_card.dart';
  import 'package:swipe_cards/swipe_cards.dart';
  import 'package:mindmatch/utils/widget_functions.dart';
  import 'package:flutter_svg/flutter_svg.dart';
  import 'package:http/http.dart' as http;
  import 'dart:convert';
  import 'package:mindmatch/utils/Auth.dart';


void main() {
  runApp(CardApp());
}

class CardApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final ThemeData themeData = Theme.of(context);
    final double padding = 25;
    final sidePadding = EdgeInsets.symmetric(horizontal: padding);

    return MaterialApp(
      home: Scaffold(
        appBar:  AppBar(
          titleSpacing: 3,
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text('Discover', style: TextStyle(color: Colors.black, fontSize: 15,),),
  
        ),
        backgroundColor: Color(0xff8f9df2),
        body: Container(
          decoration: const BoxDecoration(
          gradient: LinearGradient(
          begin: Alignment.topRight,
          end: Alignment.bottomLeft,
          colors: [Colors.white, Colors.white]
          ),
          ),
          width: size.width,
          height: size.height,
          child: Padding(
              padding: sidePadding,
              child: MyHomePage(),
            ),
        ),
      ),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {

  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var UsrID = Auth.prefs!.getString('usrid');
  var data;
  var usrpic = "";

  getData() async{
    var res = await http.get(Uri.https('www.*******.net', '/mm_api/index.php',{'act':'usrlists'}));
    data = jsonDecode(res.body);
    print(data);
    for (var i = 0; i < data.length; i++) {
      _names.add("${data[i]['fulname']}");
    }

    for (var i = 0; i < data.length; i++) {
      _images.add("${data[i]['profimage']}");
    }

    print(_names);
    print(_images);
    setState(() {});
    print(res.body);
  }


  List<SwipeItem> _swipeItems = <SwipeItem>[];
  MatchEngine? _matchEngine;
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();

  List<String> _names = [];
  List<String> _images = [];

  @override
  void initState() {
    for (int i = 0; i < _names.length; i++) {
      _swipeItems.add(SwipeItem(
        content: Content(text: _names[i], Swipeimage: _images[i]),
        likeAction: () {
          _scaffoldKey.currentState?.showSnackBar(SnackBar(
             content: Text("Liked ${_names[i]}"),
             duration: Duration(milliseconds: 500),
          ));
        },
        nopeAction: () {
          _scaffoldKey.currentState?.showSnackBar(SnackBar(
            content: Text("Nope ${_names[i]}"),
            duration: Duration(milliseconds: 500),
          ));
        },
        superlikeAction: () {
          _scaffoldKey.currentState?.showSnackBar(SnackBar(
            content: Text("Superliked ${_names[i]}"),
            duration: Duration(milliseconds: 500),
          ));
        },
        onSlideUpdate: (SlideRegion? region) async {
          print("Region $region");
        }
      ));
    }

    _matchEngine = MatchEngine(swipeItems: _swipeItems);
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final ThemeData themeData = Theme.of(context);
    final double padding = 25;
    final sidePadding = EdgeInsets.symmetric(horizontal: padding);

    return
      data != null? Stack(
        children: [
          NoMoreDataWidget(),
          SwipeCards(
            matchEngine: _matchEngine!,
            itemBuilder: (BuildContext context, int index) {
              return Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(15.0),
                      gradient: LinearGradient(
                         begin: Alignment.topRight,
                         end: Alignment.bottomLeft,
                         colors: [Colors.white, Colors.white]
                      ),
                    ),
                    width: MediaQuery.of(context).size.width,
                    child: Column(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(15.0),
                          child:
                          Image.network(
                            "https://www.*******.net/mm_api/files/profile/"+ _images[index],
                            height: 400,
                            width: MediaQuery.of(context).size.width,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children:[
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(width: 5.0),
                                Text(
                                  _names[index],
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 20
                                  ),
                                ),
                                addVerticalSpace(5),
                                Text(
                                  "Dieppe, Canada",
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 15
                                  ),
                                )
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                InkWell(
                                  onTap: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => Persondetail()
                                      ),
                                    );
                                  },
                                  child: SvgPicture.asset(
                                    'assets/images/Info.svg',
                                  ),
                                ),
                              ],
                            ),
                          ]
                        ),
                      ],
                    ),
                  )
                ],
              );
            },
            onStackFinished: () {
              _scaffoldKey.currentState!.showSnackBar(SnackBar(
                content: Text("Stack Finished"),
                duration: Duration(milliseconds: 500),
              ));
            },
            itemChanged: (SwipeItem item, int index) {
              print("item: ${item.content.text}, index: $index");
            },
            upSwipeAllowed: true,
            fillSpace: true,
          ),
        ]
      ): const Center(
        child: CircularProgressIndicator(),
      )
    ;
  }
}

class NoMoreDataWidget extends StatelessWidget {
  const NoMoreDataWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 150,
        child: Column(
          children: [
            Icon(
              Icons.error,
              size: 60.0,
              color: Colors.grey,
            ),
            Text(
              'No more data found.',
              style: TextStyle(
                fontSize: 17.0,
                color: Colors.grey[400],
              ),
            )
          ],
        ),
      ),
    );
  }
}

So clearly add the code that I add MyHomePage class in main CardApp class but when I initialize it gave me an error Null check operator used on a null value .所以清楚地添加我在主CardApp类中添加MyHomePage类的代码,但是当我初始化它时,它给了我一个错误Null check operator used on a null value

Here is my error in the console:-这是我在控制台中的错误:- 控制台中的错误图像

I notice that the getData() method is called after the for loop, therefore, the _names list is still empty when you are trying to access it.我注意到getData()方法是在 for 循环之后调用的,因此,当您尝试访问它时, _names列表仍然是空的。 Also the getData() method is async and you're not waiting for the data to be fully loaded.此外getData()方法是async的,您无需等待数据完全加载。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM