Home > Software design >  Having issues with shared preferences and settings
Having issues with shared preferences and settings

Time:02-22

I am currently having issues programming my settings page with Shared Preferences. I have 3 files currently involved and 3 errors I have researched and have no idea how to fix.

The error at Line 157 (main.Dart) says:

The method 'setState' isn't defined for the type 'Settings'. Try correcting the name to the name of an existing method, or defining a method named 'setState'.dartundefined_method

The error at Line 169 (main.dart) says:

The method 'initState' isn't defined in a superclass of 'Settings'. Try correcting the name to the name of an existing method, or defining a method named 'initState' in a superclass.dartundefined_super_member

The error at Line 20 (shared_preferences.dart) says:

The argument type 'String?' can't be assigned to the parameter type 'String'.dartargument_type_not_assignable

I'm new to Flutter, so I have been following mostly tutorials and have bought a couple courses, but I don't know how to even start fixing these errors so any help would be greatly appreciated because Stack Overflow is always great! Thank you!

main.dart (Lines 149 - 240)

// Settings Page & Account Information
class Settings extends StatelessWidget {
  Settings({Key? key}) : super(key: key);
  final _preferencesService = PreferencesService();
  final _usernameController = TextEditingController();

  void _populateFields() async {
    final settings = await _preferencesService.getSettings();
    setState(() {                                                                    // Line 157 Issue
      _usernameController.text = settings.username;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
        ? 'DarkTheme'
        : 'LightTheme';

    void initState() {
      super.initState();                                                             // Line 169 Issue
      _populateFields();
    }

    return Scaffold(
        appBar: AppBar(
          title: const Text(
              'Settings'), /* actions: <Widget>[
          IconButton(
              onPressed: () async {
                _saveSettings;
              },
              icon: const Icon(Icons.save),
              tooltip: 'Save Settings')
        ] */
        ),
        body: SingleChildScrollView(
            child: Padding(
          padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
          child: Column(
            children: [
              Column(
                // Account
                children: [
                  const Padding(
                      padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
                      child: Text('Account Information',
                          style: TextStyle(
                            fontSize: 17.0,
                          ))),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                    child: TextField(
                      controller: _usernameController,
                      inputFormatters: [LengthLimitingTextInputFormatter(25)],
                      decoration: InputDecoration(
                        hintText: 'Username',
                        labelText: 'Username',
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0)),
                      ),
                    ),
                  ),
                ],
              ),
              Container(
                child: Column(
                  // App Settings
                  children: [
                    // SwitchListTile(value: DarkMode, onChanged: Light => Dark => Light)
                    // ChangeThemeButtonWidget(),
                    TextButton(
                        onPressed: _saveSettings,
                        child: const Text('Save Settings'))
                  ],
                ),
              ),
            ],
          ),
        )));
  }

  void _saveSettings() {
    final newSettings = SettingsModal(
      username: _usernameController.text,
    );

    print(newSettings);
    print(_usernameController.text);
    _preferencesService.saveSettings(newSettings);
  }
}

shared_preferences.dart

import 'package:bit/main.dart';
import 'package:bit/saved_data.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PreferencesService {
  Future saveSettings(SettingsModal settings) async {
    final preferences = await SharedPreferences.getInstance();

    await preferences.setString('username', settings.username);

    print('Saved Settings');
  }

  Future<SettingsModal> getSettings() async {
    final preferences = await SharedPreferences.getInstance();

    final username = preferences.getString('username');

    return SettingsModal(
      username: username,                                                             // Line 20 Issue
    );
  }
}

saved_data.dart

import 'package:shared_preferences/shared_preferences.dart';
import 'package:bit/main.dart';

class SettingsModal {
  final String username;

  SettingsModal({
    required this.username,
  });
}

CodePudding user response:

I would recommend you to read this: https://docs.flutter.dev/development/ui/interactive.

But, answering your questions:

  1. Error at line 157: Your Settings class is a stateless widget, so.. you can't set any state to that widget because it doesn't have state. If you want to add state you need to make Settings a Stateful Widget.

  2. Error at line 169: as your Settings class extends from Stateless widget, it's super also doesn't have initState method. Again, you should make your Settings class a stateful widget.

  3. Error in sharedpreferences: getString method can be null, so its type is String, meanwhile username is required, so you have these options:

Opt 1:

final username = preferences.getString('username')!;

Opt 2:

final username = preferences.getString('username') ?? "";
  • Related