Home > Enterprise >  Why variables in a class not getting changed ? Flutter
Why variables in a class not getting changed ? Flutter

Time:03-20

I just started learning flutter I needed to pass data between pages so I found it easy to do with static variables but now I'm trying to make a setting page. I made a class named Settings like this :

class Settings {


static bool darkMode = false;
  static bool addTable = true;
  static saveSetting() {
    GetStorage().write("darkMode", Settings.darkMode);
    GetStorage().write("addTable", Settings.addTable);
  }

  static setSetting() {
    GetStorage.init();
    Settings.darkMode = (GetStorage().read("darkMode") ?? false);
    Settings.addTable = (GetStorage().read("addTable") ?? true);
  }
}

And a Switch in that page like this :

Switch(
      value: Settings.addTable,
      onChanged: (_) {
        setState(() {
          Settings.addTable = !Settings.addTable;
           Settings.saveSetting();
                  });
                }),

but after reloading the app the values are not saved in GetStorage, strings are saved perfectly except this one.

And the whole code is here :

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'widgets/menu_button.dart';

void main() async {
  await GetStorage.init();
  DataManagament dataManagament = DataManagament();
  dataManagament.startingApp();
  runApp(const MyApp());
}

class DataManagament {
  static String reserveString = "";
  static List<String> reserveList = [];
  static String tableString = "";
  static List<String> tableList = [];
  void saveReserveList() {
    GetStorage().write("reserveList", reserveList.toString());
  }

  void saveTableList() {
    GetStorage().write("tableList", tableList.toString());
  }

  void startingApp() {
    Settings.setSetting;
    //reserve
    reserveString = (GetStorage().read("reserveList") ?? "");
    reserveString == ""
        ? reserveList = []
        : reserveList =
            reserveString.substring(1, reserveString.length - 1).split(",");
    //table
    tableString = (GetStorage().read("tableList") ?? "");
    tableString == ""
        ? tableList = []
        : tableList =
            tableString.substring(1, tableString.length - 1).split(",");
  }
}

class Settings {
  static bool darkMode = false;
  static bool addTable = true;
  static saveSetting() {
    GetStorage().write("darkMode", Settings.darkMode);
    GetStorage().write("addTable", Settings.addTable);
  }

  static setSetting() {
    Settings.darkMode = (GetStorage().read("darkMode") ?? false);
    Settings.addTable = (GetStorage().read("addTable") ?? true);
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: IntroPage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

//
//
//************************************************************
//
//

//
//
//************************************************************
//          Reserve Page
//

class ReservePage extends StatefulWidget {
  const ReservePage({Key? key}) : super(key: key);

  @override
  State<ReservePage> createState() => _ReservePageState();
}

class _ReservePageState extends State<ReservePage> {
  final _nameController = TextEditingController();
  final _minuteController = TextEditingController();
  final _hourController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  content: SingleChildScrollView(
                    child: Column(
                      children: [
                        TextField(
                          controller: _nameController,
                          textDirection: TextDirection.rtl,
                          decoration: const InputDecoration(
                            hintTextDirection: TextDirection.rtl,
                            border: OutlineInputBorder(),
                            labelText: 'نام',
                          ),
                        ),
                        Row(
                          children: [
                            Expanded(
                              flex: 5,
                              child: TextField(
                                controller: _hourController,
                                maxLength: 2,
                                keyboardType: TextInputType.number,
                                decoration: const InputDecoration(
                                  labelText: 'hour',
                                ),
                              ),
                            ),
                            const Expanded(
                              flex: 3,
                              child: Center(
                                child: Text(
                                  ":",
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                            Expanded(
                              flex: 5,
                              child: TextField(
                                controller: _minuteController,
                                maxLength: 2,
                                keyboardType: TextInputType.number,
                                decoration: const InputDecoration(
                                  labelText: 'minute',
                                ),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 20),
                        Center(
                          child: OutlinedButton(
                            onPressed: () {
                              if (_hourController.text != "" &&
                                  _nameController.text != "") {
                                setState(() {
                                  DataManagament.reserveList
                                      .add(_nameController.text);
                                  DataManagament.reserveList.add(
                                      "${_hourController.text}:${_minuteController.text}");
                                  _hourController.clear();
                                  _nameController.clear();
                                  _minuteController.clear();
                                  DataManagament().saveReserveList();
                                });
                              }
                            },
                            child: const Text(
                              "save",
                              style: TextStyle(
                                color: Colors.black,
                              ),
                            ),
                            style: OutlinedButton.styleFrom(
                              minimumSize: Size(
                                size.width / 3,
                                (size.width / 3) * 0.4,
                              ),
                              backgroundColor: Colors.green,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  title: const Center(child: Text("")),
                );
              });
        },
        child: const FittedBox(
          child: Icon(
            Icons.add,
          ),
        ),
      ),
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        title: const Text(
          "",
        ),
        centerTitle: true,
      ),
      body: DataManagament.reserveList.isNotEmpty
          ? SingleChildScrollView(
              child: Column(
                children: [
                  ListView.builder(
                    shrinkWrap: true,
                    itemCount: DataManagament.reserveList.length ~/ 2,
                    itemBuilder: (BuildContext context, int index) {
                      return Card(
                          // name 0 , time ,1
                          child: ListTile(
                        //name
                        trailing: Text(
                          DataManagament.reserveList[index * 2],
                        ),
                        //time
                        title: Text(
                          DataManagament.reserveList[(index * 2)   1],
                        ),
                        leading: TextButton(
                          onPressed: () {
                            setState(() {
                              DataManagament.reserveList.removeAt(index * 2);
                              DataManagament.reserveList.removeAt(index * 2);
                              DataManagament().saveReserveList();
                            });
                          },
                          child: const Text("delete"),
                        ),
                      ));
                    },
                  ),
                ],
              ),
            )
          : const Center(
              child: Text("..."),
            ),
    );
  }
}

//
//
//************************************************************
//          Menu Page
//

class MenuPage extends StatelessWidget {
  const MenuPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const SettingsPage(),
                  ));
            },
            icon: const Icon(Icons.settings),
          ),
        ],
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        centerTitle: true,
        title: const Text(
          "",
        ),
      ),
      body: Column(
        children: [
          const Spacer(flex: 1),
          Expanded(
              child: Center(
                child: MenuButton(
                    func: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const TablePage(),
                          ));
                    },
                    text: "tables"),
              ),
              flex: 2),
          Expanded(
              child: Center(
                child: MenuButton(
                    func: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ReservePage(),
                          ));
                    },
                    text: "رزروها"),
              ),
              flex: 2),
          Expanded(
              child: Center(
                child: MenuButton(func: () {}, text: "test"),
              ),
              flex: 2),
          const Spacer(
            flex: 4,
          )
        ],
      ),
    );
  }
}

//
//
//************************************************************
//          Tables Page
//

class TablePage extends StatefulWidget {
  const TablePage({Key? key}) : super(key: key);

  @override
  State<TablePage> createState() => _TablePageState();
}

class _TablePageState extends State<TablePage> {
  final _nameController = TextEditingController(); // ignore: unused_field

  final _minuteController = TextEditingController(); // ignore: unused_field

  final _hourController = TextEditingController(); // ignore: unused_field

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: Settings.addTable
          ? GestureDetector(
              onLongPress: () {
                setState(() {
                  Settings.addTable = false;
                });
              },
              child: FloatingActionButton(
                onPressed: () {
                  setState(() {
                  });
                },
                child: const Icon(
                  Icons.add,
                ),
              ),
            )
          : null,
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        title: const Text(
          "tables",
        ),
        centerTitle: true,
      ),
      body: DataManagament.tableList.isNotEmpty
          ? SingleChildScrollView(
              child: Column(
                children: [
                  ListView.builder(
                    shrinkWrap: true,
                    itemCount: DataManagament.tableList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Card(
                        // name 0 , time ,1
                        child: ListTile(
                          //name
                          trailing: Row(
                            children: [
                              Text(index.toString()),
                              TextButton(
                                onPressed: () {
                                  setState(() {
                                    DataManagament.tableList[index] =
                                        _nameController.text;
                                  });
                                },
                                child: const Text(""),
                              ),
                            ],
                          ),
                          //time
                          title: TextButton(
                            onPressed: () {},
                            child: const Text(""),
                          ),
                          leading: TextButton(
                            onPressed: () {},
                            child: Text(
                                DataManagament.tableList[index].toString()),
                          ),
                        ),
                      );
                    },
                  ),
                ],
              ),
            )
          : const Center(
              child: Text("..."),
            ),
    );
  }
}

//
//
//************************************************************
//          Intro Page
//

class IntroPage extends StatefulWidget {
  const IntroPage({Key? key}) : super(key: key);

  @override
  State<IntroPage> createState() => _IntroPageState();
}

class _IntroPageState extends State<IntroPage> {
  Timer? _timer;

  void startTimer() {
    _timer = Timer(const Duration(seconds: 3), () {
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => const MenuPage(),
          ));
    });
  }

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

  @override
  void dispose() {
    _timer!.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
              child: Center(
                child: Image.asset("images/eightball.png"),
              ),
              flex: 4),
          const Expanded(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        ],
      ),
    );
  }
}

//
//
//************************************************************
//          Settings Page
//

class SettingsPage extends StatefulWidget {
  const SettingsPage({Key? key}) : super(key: key);

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        title: const Text("settings"),
      ),
      body: ListView(children: [
        Card(
          child: ListTile(
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: const [
                Text(
                  "add table",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(width: 10),
                Icon(Icons.add, size: 30),
              ],
            ),
            leading: Switch(
                value: Settings.addTable,
                onChanged: (_) {
                  setState(() {
                    Settings.addTable = !Settings.addTable;
                    Settings.saveSetting();
                  });
                }),
          ),
        ),
        Card(
          child: ListTile(
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: const [
                Text(
                  "night mode",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(width: 20),
                Icon(Icons.dark_mode),
              ],
            ),
            leading: Switch(
                value: Settings.darkMode,
                onChanged: (_) {
                  setState(() {
                    Settings.darkMode = !Settings.darkMode;

                    Settings.saveSetting();
                  });
                }),
          ),
        ),
      ]),
    );
  }
}

CodePudding user response:

You need to call

final settings = new Settings();
settings.setSettings();

in a page where you want to access settings

CodePudding user response:

I think you are just reading data from GetStorage inside setSettings instead of writing to storage, so when the app releods or restarts data inside static variables will not be available. as:

static setSetting() {
    GetStorage.init();
    Settings.darkMode = (GetStorage().read("darkMode") ?? false);
    Settings.addTable = (GetStorage().read("addTable") ?? true);
    //Here you are just updating your settings variable.
    //Update you storage also to keep the selection in storage 
  }

Hope it works.

  • Related