flutter future change value when inside future builder

1.6k Views Asked by At

hello I'm new to flutter and building my first app , can I change a value in future function in builder based on a value change then reset it to the way it was when app is terminated ? Archive.dart


class _ArchiveState extends State<Archive> {
  Future<List<YearsMain>> downloadJSONMain() async {
    String year;
    SharedPreferences pref = await SharedPreferences.getInstance();
    year = pref.getString('year');
    final jsonEndpoint = "http://msc-mu.com/api_verfication.php";

    final response = await http.post(jsonEndpoint, body: {
      'flag': 'selectmainsubjects',
      'year': year,
    });

    if (response.statusCode == 200) {
      List mainSubject = json.decode(response.body);
      return mainSubject.map((mains) => new YearsMain.fromJson(mains)).toList();
    } else
      throw Exception(
          'We were not able to successfully download the Main Subjects.');
  }
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: new FutureBuilder<List<YearsMain>>(
          future: downloadJSONMain(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<YearsMain> mains = snapshot.data;
              return ListViewMain(mains);
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

I want to implement a dropdown list wo change the "year" value in the future function and when the app is closed I want that value to get back the way it was , is there any way to do that or by putting another string I don't know actually , any help ?

1

There are 1 best solutions below

4
On

You can use DropdownButton to allow users to change the year. But before, move your future logic to the initState. Use Dropdown's "onChanged" callback to update your sharedPreferences instance and the future, inside a setState. Here's an example:

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Future future;
  String selectedYear = "2020";

  @override
  void initState() {
    future = downloadJSONMain(); // or just set the "future" variable inside the "downloadJSONMain function
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: dropdownValue,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String newValue) {
        setState(() {
          selectedYear = newValue;
          // update the future once user select a new year
          future = downloadJSONMain();
          // also save it to the sharedPrefeences here
          // ...

        });
      },
      items: <String>["2017", "2018", "2019", "2020"]
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}