在未来的构建者内部时波动未来的变化值

问题描述

您好,我是第一个开始构建应用程序的人,我可以基于值更改来更改builder中未来功能的值,然后将其重置为应用程序终止时的状态吗? 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();
          },),);
  }
}

我想实现一个下拉列表,以在将来的功能中更改“年份”值,当应用关闭时,我希望该值恢复原状,是否有任何方法可以做到这一点,也可以通过放置另一个我实际上不知道的字符串,有什么帮助吗?

解决方法

您可以使用DropdownButton来允许用户更改年份。但是在此之前,请将您将来的逻辑移至initState。使用Dropdown的“ onChanged”回调在setState中更新您的sharedPreferences实例和将来的实例。这是一个示例:

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(),);
  }
}