Home > Back-end >  NoSuchMethodError: The method '[]' was called on null. Receiver: null
NoSuchMethodError: The method '[]' was called on null. Receiver: null

Time:02-24

Hey guys am new to flutter and i have been having this issue of displaying data to screen. my error

NoSuchMethodError: The method '[]' was called on null. Receiver: null

my code

class _DashboardState extends State<Dashboard> {
  var user;
  Future getUserDT() async {
    Map data = await getStored_user('login');
    setState(() {
      user = data;
    });
  }

  @override
  void initState() {
    super.initState();
    getUserDT();
  }

where i get the error

              Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "${user['user']['user_name']}" //this is where i get the error,
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                            color: kBlueColor,
                            fontFamily: kQuicksand,
                          ),
                        ),
                        

trying to display user info to the screen

CodePudding user response:

In your getUserDT() until the getStored_user() method is not done, setState() function doesn't get called. So when the build() function runs and if the setState() method is still not called you get this error.

  Future getUserDT() async {
    Map data = await getStored_user('login');
    
    //THIS DOESN'T GET CALLED UNTIL getStored_user() is done
    setState(() {
      user = data;
    });
  }

Because you are using Future, you should use FutureBuilder. And don't call getUserDT() in initState() anymore.

FutureBuilder(
  future: getUserDT,
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) =>
      snapshot.hasData ? Text('user') : Text('Loading'),
),

CodePudding user response:

EDIT: Based on your initState(), flutter first calls build() method, then getUserDT() (which then calls another time the build() method).

You are getting the error because user is null the first time build method is called.

You should use a FutureBuilder:

   FutureBuilder(
    future: getUserDT(),
    builder: (context, snap) {
      if (snap.hasData) {
        var user = snap.data!;
        return Column(
         children: [
          Padding(
           padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
           child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
             Text(
              "${user['user']['user_name']}"
              style: TextStyle(
               fontSize: 24,
               fontWeight: FontWeight.bold,
               color: kBlueColor,
               fontFamily: kQuicksand,
              ),
             ),
            ],
           ),
          ),
         ],
        );
      } else if (snap.hasError) {
        return Container();
      } else {
        return Center(child: CircularProgressIndicator(color: Colors.blue));
      }
    });

WRONG ANSWER (NOT TO BE USED):

Change initState()

@override
  void initState() {
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      getUserDT();
    });
    super.initState();
    
  }
  • Related