0

Hello I use shared preferences and dropdown for saving the screen value in the app but after I add code of shared preferences its shows following error but if I delete the shared preferences code then dropdown works fine. Without shared perferences the dropdown is working . but after i add code of shared perference to save my dropdown value then this error comes . This is error show in my app

This is my full code

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: DropPage());
  }
}

class DropPage extends StatefulWidget {
  @override
  _DropPageState createState() => _DropPageState();
}

class _DropPageState extends State<DropPage> {
  String _selectedGender = 'FYJC';
  SharedPreferences prefs;
  final _key = 'cur_r';

  @override
  void initState() {
    super.initState();
    _read(); // read in initState
  }

  _read() async {
    prefs = await SharedPreferences.getInstance();
    setState(() {
      _selectedGender = prefs.getString(_key) ?? "FYJC"; // get the value
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            DropdownButton(
              value: _selectedGender,
              items: _dropDownItem(),
              onChanged: (value) {
                setState(() {
                  _selectedGender = value;
                });
                prefs.setString(
                    _key, _selectedGender); // save value to SharedPreference

                _selectedGender = value;
                switch (value) {
                  case "FYJC":
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondScreen()),
                    );
                    break;
                  case "SYJC":
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondScreen()),
                    );
                    break;
                  case "FYBCOM":
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondScreen()),
                    );
                    break;
                  case "SYBCOM":
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondScreen()),
                    );
                    break;
                  case "TYBCOM":
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondScreen()),
                    );
                    break;
                }
              },
              hint: Text('Select Cource Year'),
            ),
          ],
        ),
      ),
    );
  }

  List<DropdownMenuItem<String>> _dropDownItem() {
    List<String> ddl = [
      "FYJC",
      "SYJC",
      "FYBCOM",
      "SYBCOM",
      "TYBCOM",
    ];
    return ddl
        .map((value) => DropdownMenuItem(
              value: value,
              child: Text(value),
            ))
        .toList();
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Screen"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}


NIKHIL 27
  • 41
  • 1
  • 5

1 Answers1

0

I can not reproduce the error with the given code. Can you be more specific as to when the error occurs?

Your code sample from above

Maybe this will help link

 _read() async {
    prefs = await SharedPreferences.getInstance();
    setState(() {
      final cachedValue = prefs.getString(_key);
      if(cachedValue != null)
        _navigate(cachedValue);

      _selectedGender = cachedValue ?? "FYJC"; // get the value
    });
  }
 ...

void _navigate(value) {
    switch (value) {
      case "FYJC":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SecondScreen()),
        );
        break;
      case "SYJC":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SecondScreen()),
        );
        break;
      case "FYBCOM":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SecondScreen()),
        );
        break;
      case "SYBCOM":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SecondScreen()),
        );
        break;
      case "TYBCOM":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SecondScreen()),
        );
        break;
    }
  }

There is problems with this approach.

I think it would be better to use something like this:

home: expression ? DropPage() : SelectedPage(),

The expression can evaluate, whether or not a user has already selected an item. But in that case the user will not be able to go back to the dropdown menu, because the page will never be on the stack.

snicz
  • 61
  • 7
  • means 1st I add code of dropdown then dropdown work fines but after this code, I add shared perf code to save this screen then its error shows – NIKHIL 27 Jun 07 '20 at 10:20
  • I edited my answer with a working project from your Code – snicz Jun 07 '20 at 10:23
  • but how to save the screen means i click on tybcom then its navigate me to next screen but next screen not save in shred perf i click on back button then its come back to select dropdown – NIKHIL 27 Jun 07 '20 at 10:27
  • So the problem you are facing is, that when you are clicking on the "Go back!" button, your selected item is not "tybcom" anymore? – snicz Jun 07 '20 at 10:29
  • means how to store the particular screen from the dropdown means i click 1 item in dropdown then its navigate me to this screen after i closed the app then its need to open the seleted screen not dropdown screen – NIKHIL 27 Jun 07 '20 at 10:31
  • In order to do that, you have to dynamically build your App, instead of building it statically. That means, your code is working as expected and the App calling 'HomeView' has to dynamically decide what page to show. Or you could do something like navigate based on a cached value (see my answer). – snicz Jun 07 '20 at 10:36
  • https://drive.google.com/file/d/1LrfTY6INJduYuTb9yEDHI24rflJi75_l/view?usp=sharing – NIKHIL 27 Jun 07 '20 at 10:37
  • this video is help you to understand means when i select the tybcom then tybcom screen open but i won't to store the tybcom screen in data when i click back its go to dropdown screen – NIKHIL 27 Jun 07 '20 at 10:39
  • means i need dropdown 1 time only when newly app opens like select course if user select tybcom course from the dropdown then user goes to tybcom screen after user closed the app then user need to tybcom screen not on dropdown screen – NIKHIL 27 Jun 07 '20 at 10:47
  • Glad I could help. In order to clean up the code a bit further you should take a look into state management. I prefer bloc. – snicz Jun 07 '20 at 11:01