5
votes

I build a function that is used to store the token in shared preference and then fetch data from the server when I run my app for the very first time an error appears

The following NoSuchMethodError was thrown building AdminPage(dirty, state: AdminPageState#87bcd): flutter: The method '[]' was called on null. flutter: Receiver: null flutter: Tried calling:

and then the app works fine

P.S. my code is that

Future<Map<String, dynamic>> getCards(String userid) async {
  BuildContext context;
  String jWTtoken = '';
  try {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    //  prefs = await SharedPreferences.getInstance();
    jWTtoken = prefs.getString('token');
    tokenfoo();
  } catch (e) {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (BuildContext context) => AuthPage()),
    );
  }

  final Map<String, dynamic> authData = {
    'Userid': '261',
    // 'Email':_formData['Email'],
    // 'Password':_formData['Password'],
  };

  final http.Response response = await http.post(
      'hurl',
      body: json.encode(authData),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + jWTtoken
      });

  final Map<String, dynamic> responseData = json.decode(response.body);

  if (responseData["StatusCode"] == 200) {

    null;
  
  } else if (responseData["StatusCode"] == 401) {
    print(responseData);
    Logout();
  } else {
    print(responseData);
    Logout();

    null;
  }
  return responseData;
}

anything worng with it?

and in the debug mode the error appears in this line

 final SharedPreferences prefs = await SharedPreferences.getInstance();

the error :

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ flutter: The following NoSuchMethodError was thrown building AdminPage(dirty, state: AdminPageState#7db9a): flutter: The method '[]' was called on null. flutter: Receiver: null flutter: Tried calling: flutter: flutter: When the exception was thrown, this was the stack: flutter:

0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5) flutter: #1

AdminPageState.build (package:idb/pages/adminpage.dart:63:39) flutter:

2 StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27) flutter: #3

ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15) flutter: #4
Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5) flutter: #5 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5) flutter: #6
StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3848:11) flutter: #7
ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5) flutter: #8
Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14) flutter: #9
Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12) flutter: #10
ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16) flutter: #11
Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5) flutter: #12 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33) flutter: #13
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20) flutter: #14
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5) flutter: #15
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15) flutter: #16
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9) flutter: #17
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5) flutter: #18
_invoke (dart:ui/hooks.dart:154:13) flutter: #19 _drawFrame (dart:ui/hooks.dart:143:3)

2
Please post the stack trace !Rakesh Lanjewar
how to do that 😅Tabarek Ghassan
Have you tried removing the final modifier on the line? It makes no sense to make it a final.R. Duggan
error may be at jWTtoken = prefs.getString('token') check for it. And post the complete error you get.Amol Gangadhare
the error seems to be in adminpage.dart file refer line number 63 in adminpage. Is the error occurs continuously or occurs some times only? Can you provide adminpage code?Amol Gangadhare

2 Answers

1
votes

Possibly because jwToken is empty at initialization. Try giving jwToken a string value such as "test".

0
votes

This is happening because you don't initialize it before use

To avoid this you should initialize await SharedPref.init(); it on a _MyAppState class in initState() method like this

class _MyAppState extends State<MyApp> {

  void initState() async {
    super.initState();
    await SharedPref.init();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      locale: _locale,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: appThemeColor,
        accentColor: Colors.lightBlueAccent,
      ),
      home: SplashScreen(),
      builder: (BuildContext context, Widget child) {
        return child;
      },
    );
  }
}

Create a global class to use globally

class SharedPref {
  static SharedPreferences pref;
  static Future init() async {
    pref = await SharedPreferences.getInstance();
  }
}

After you can use like this

SharedPref.pref.setBool("isLogin", true);