简体   繁体   中英

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

I want to add data from database on 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. 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.

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 .

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. Also the getData() method is async and you're not waiting for the data to be fully loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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