简体   繁体   English

颤振:在空值上使用空检查运算符?

[英]flutter: Null check operator used on a null value?

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:mindmatch/screens/Sidebar.dart';
import 'package:mindmatch/screens/Footer.dart';
import 'package:mindmatch/screens/Persondetail.dart';
import 'package:mindmatch/screens/Congratulations.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,),),
      leading: Builder(
        builder: (BuildContext context) {
          return Padding(padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
            child: IconButton(
              icon: SvgPicture.asset(
                width: 30,
                'assets/images/Menu.svg',
                height: 30,
              ),
              onPressed: () { Scaffold.of(context).openDrawer(); },
              tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
            ),
          );
        },
      ),
      actions: <Widget>[
        Padding(
            padding: sidePadding,
            child: Row(
              children: [
                //Icon(Icons.search, color: Colors.black,),
                SvgPicture.asset(
                  width: 30,
                  'assets/images/search.svg',
                  height: 30,
                ),
                addHorizontalSpace(10),
                //Icon(Icons.doorbell_outlined, color: Colors.black),
                SvgPicture.asset(
                  width: 30,
                  'assets/images/notifications.svg',
                  height: 30,
                )
              ],
            )

        )

      ],
    ),
    backgroundColor: Color(0xff8f9df2),
    //body: MyHomePage(),
    body: Container(
      decoration: const BoxDecoration(
      gradient: LinearGradient(
      begin: Alignment.topRight,
      end: Alignment.bottomLeft,
      //colors: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
      colors: [Colors.white, Colors.white]
      ),
      ),
      width: size.width,
      height: size.height,
      child: Padding(
          padding: sidePadding,
          child: MyHomePage(),
        ),
    ),
    drawer: Sidebar(),

    persistentFooterButtons: [
      Footer(),
    ],
  ),
  debugShowCheckedModeBanner: false,
);
}
}

class MyHomePage extends StatefulWidget {

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

 //final String? title;

 @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.algowid.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], /*location: _locate[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: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
                        colors: [Colors.white, Colors.white]
                    ),
                  ),
                  //height: MediaQuery.of(context).size.height,
                  width: MediaQuery.of(context).size.width,
                  child: Column(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(15.0),
                        child:
                        Image.network(
                          "https://www.algowid.net/mm_api/files/profile/"+ _images[index],
                          height: 400,
                          width: MediaQuery.of(context).size.width,
                          fit: BoxFit.cover,
                          //height: 150,
                          //scale: 2.5,
                        ),
                        // Image.asset(
                        //   _images[index],
                        //   height: 400,
                        //   width: MediaQuery.of(context).size.width,
                        //   fit: BoxFit.cover,
                        //   //height: 150,
                        //   //scale: 2.5,
                        // ),
                      ),
                      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(
                                  //_locate[index],
                                  "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',
                                    //width: 70,
                                    //height: 70,
                                  ),
                                ),
                              ],
                            ),
                          ]
                      ),
                      //addVerticalSpace(20),
                    ],
                  ),
                )

              ],
            );

          },
          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,
        ),

        Positioned(
          bottom: 20,
          right: -30,
          //right: 0,
          width: MediaQuery.of(context).size.width,
          child: Padding(
            padding: EdgeInsets.fromLTRB(40, 25, 40, 25),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:[
                  Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[

                          InkWell(
                            onTap: (){},
                            child: CircleAvatar(
                              radius: 15.0,
                              backgroundColor: Color(0xff8f9df2),
                              child: IconButton(
                                icon: Icon(
                                  Icons.refresh,
                                  color: Colors.white,
                                  size: 15,
                                ),
                                onPressed: () {},
                              ),
                            ),
                          ),
                          SizedBox(width: 40.0),
                          CircleAvatar(
                            radius: 25,
                            backgroundColor: Color(0xffff4040),
                            child: IconButton(
                              icon: Icon(
                                Icons.close,
                                color: Colors.white,
                              ),
                              onPressed: () {
                                _matchEngine!.currentItem?.nope();
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          CircleAvatar(
                            radius: 25,
                            backgroundColor: Color(0xff50c75c),
                            child: IconButton(
                              icon: Icon(
                                Icons.favorite_border,
                                color: Colors.white,
                              ),
                              onPressed: () {
                                //_matchEngine!.currentItem?.like();
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) => Congratulations()),
                                );
                              },
                            ),
                          ),
                          SizedBox(width: 40.0),
                          CircleAvatar(
                            radius: 15,
                            backgroundColor: Color(0xff8f9df2),
                            child: IconButton(
                              icon: Icon(
                                Icons.star_border,
                                color: Colors.white,
                                size: 15,
                              ),
                              onPressed: () {
                                _matchEngine!.currentItem?.superLike();
                              },
                            ),
                          ),
                          SizedBox(width: 10.0),
                        ],
                      ),
                    ],
                  ),
                ]
            ),
          ),
        )
      ]
  ): 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:-这是我在控制台中的错误:- 控制台中的错误图像

Null check operator used on a null value simply means you somewhere use ! Null check operator used on a null value仅意味着您在某处使用! on a variable that's null.在一个为空的变量上。 If the error is in the code you showed us it must be one (or more) of the following:如果错误出现在您向我们展示的代码中,则它必须是以下一项(或多项):

Auth.prefs!
_matchEngine!
_scaffoldKey.currentState!

Make sure all of those are not null where you use them.确保所有这些在您使用它们的地方都不为null

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

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