Flutter,如何从返回的Widget调用有状态Widget内部的函数?

nwsw7zdq  于 2022-12-24  发布在  Flutter
关注(0)|答案(2)|浏览(183)

我想把我的脚手架分解成更小的部分以便于阅读。我把小部件分成函数并返回到脚手架树。但是我不知道如何使用有状态小部件中声明的函数,它需要设置UI的状态。
我的代码的一部分:

Future<List<dataRecord>>? dataList;

class _clientDetailState extends State<clientDetail> {
  @override
  void initState() {
    super.initState();
  }

  List<dataRecord> parseJson(String responseBody) {
    final parsed =
        convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
  }

  Future<List<dataRecord>> fetchData(http.Client client) async {
    final response = await client
        .get(Uri.parse('test.php'));
    return parseJson(response.body);
  }

  Body: myButton,
        ListView,
Widget myButton() {
  return TextButton(
    child: Text('test'),
    onTap: () {
      dataList = fetchData(http.Client());   //Method not found
    },
}
ppcbkaq5

ppcbkaq51#

下面是简单的做法

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

  @override
  State<ClientDetail> createState() => _ClientDetailState();
}

class _ClientDetailState extends State<ClientDetail> {

  List<dataRecord> dataList = [];

  @override
  Widget build(BuildContext context) {
    return ListView(
  children: [
      myButton(),
      ...dataList.map((e) => Text(e)).toList(),
     ],
    );
  }

  List<dataRecord> parseJson(String responseBody) {
    final parsed =
        convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
  }

  Future<List<dataRecord>> fetchData(http.Client client) async {
    final response = await client.get(Uri.parse('test.php'));
    return parseJson(response.body);
  }

  Widget myButton() {
    return TextButton(
        child: const Text('test'),
        onPressed: () async {
          setState(() async {
            dataList = await fetchData(http.Client());
          });
        });
  }
}

提示:类名始终以大写字母开头,例如,ClientDetail而不是clienDetail以及DataRecord而不是dataRecord

问候

kr98yfug

kr98yfug2#

您可以将实际函数作为参数传递给小部件的函数,然后直接从state调用它;

Body: myButton(onPressed: () => fetchData(http.Client())),
ListView,

Widget myButton({required void Function()? onPressed}) {
  return TextButton(
    child: Text('test'),
    onPressed: onPressed,
  );
}

相关问题