0

你好我是新来的颤振和构建我的第一个应用程序,我可以根据值更改在构建器中更改未来函数中的值,然后将其重置为应用程序终止时的方式吗? 存档.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();
          },
        ),
      ),
    );
  }
}

我想实现一个下拉列表来更改未来函数中的“年份”值,当应用程序关闭时,我希望该值恢复原来的状态,有没有办法做到这一点或通过放置另一个字符串我不真的不知道,有什么帮助吗?

4

1 回答 1

0

您可以使用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(),
    );
  }
}
于 2020-10-10T17:44:12.373 回答