Napoleon Wai Lun Wong
Napoleon Wai Lun Wong

Reputation: 67

Flutter SharedPreferences non-nullable instance fields

I have a problem when I want to using the shared preferences to store and display the value. On the code, I would need to create the public class for the bellow function to use. However it would return the follow error:

error: Non-nullable instance field 'sharedPreferences' must be initialized. (not_initialized_non_nullable_instance_field at [login] lib/main.dart:32)

SharedPreferences sharedPreferences; //line:32

Here is my full code.


import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:login/login_page.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Code Land",
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
      theme: ThemeData(
          accentColor: Colors.white70
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
   createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {

  SharedPreferences sharedPreferences;

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

  checkLoginStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
    if(sharedPreferences.getString("token") == null) {
      Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Code Land", style: TextStyle(color: Colors.white)),
        actions: <Widget>[
          FlatButton(
            onPressed: () {
              sharedPreferences.clear();
              sharedPreferences.commit();
              Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
            },
            child: Text("Log Out", style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
      body: Center(child: Text("Main Page")),
      drawer: Drawer(),
    );
  }
}```

Upvotes: 2

Views: 321

Answers (3)

J. S.
J. S.

Reputation: 9625

From the Dart documentation: "The late modifier lets you use non-nullable types and final in places you otherwise might not be able to, at the expense of runtime checking. It also gives you lazy-initialized fields." https://dart.dev/null-safety/understanding-null-safety

Your SharedPreferences declaration should have the late modifier:

late SharedPreferences sharedPreferences;

Upvotes: 0

Benyamin
Benyamin

Reputation: 1144

change the line like this for the compiler to know that you will initialize it later:

late SharedPreferences sharedPreferences;

Upvotes: 3

Csisanyi
Csisanyi

Reputation: 885

This should do the trick, if you don't intend to initialize sharedPref right away.

SharedPreferences? sharedPreferences;

Dart sound null safety has been enabled as default in flutter since 2.2 if I'm correct.

Check out this article for a starter on the topic.

https://dart.dev/null-safety

Upvotes: 1

Related Questions