如何从另一个StatefulWidget调用有状态Widget中的函数?

时间:2020-11-08 17:38:33

标签: function flutter call stateful

你好,我想调用formCliente类的StatefulWidget内的函数来清理控制器。但是我想通过formFinanceiro类的StatefulWidget内的按钮来访问它。请帮帮我!谢谢。

      class _CadastrarClienteState extends State<CadastrarCliente>
with TickerProviderStateMixin {     
    body: Form(
      key: formkey,
      child: TabBarView(
        physics: physics, //NeverScrollableScrollPhysics()
        controller: _tabController,
        children: [
          FormCliente(),
          FormDocumento(),
          FormVeiculo(),
          FormContrato(),
          FutureBuilder(
              future: getTrabalhaComCota(),
              builder: (context, snapshot) {
                if (snapshot.hasData && !snapshot.hasError) {
                  //   print(' chamada cota:${snapshot.data}');
                  return FormFinanceiro(
                      itemsCota: snapshot.data, formKey: formkey);
                } else {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
              }),
        ],
      ),
    ),

} ]

2 个答案:

答案 0 :(得分:0)

您可以使用流实现相同的效果,请参见下面的代码:

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

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text("Demo")),
        body: MyApps(),
      ),
    );
  }
}

class MyApps extends StatefulWidget {
  @override
  _MyAppsState createState() => _MyAppsState();
}

class _MyAppsState extends State<MyApps> {
  final changeNotifier = new StreamController.broadcast();

  @override
  void dispose() {
    changeNotifier.close();
    super.dispose();
  }

  buttonClicked() => changeNotifier.sink.add(null);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        FormCliente(
          shouldTriggerChange: changeNotifier.stream,
        ),
        FormFinanceiro(buttonClicked: buttonClicked),
      ],
    );
  }
}

class FormCliente extends StatefulWidget {
  final Stream shouldTriggerChange;

  FormCliente({this.shouldTriggerChange});

  @override
  _FormClienteState createState() => _FormClienteState();
}

class _FormClienteState extends State<FormCliente> {
  StreamSubscription streamSubscription;

  @override
  initState() {
    super.initState();
    if (widget.shouldTriggerChange != null) {
      streamSubscription =
          widget.shouldTriggerChange.listen((_) => clearYourFormMethod());
    }
  }

  @override
  didUpdateWidget(FormCliente old) {
    super.didUpdateWidget(old);
    if (widget.shouldTriggerChange != old.shouldTriggerChange) {
      streamSubscription.cancel();
      streamSubscription =
          widget.shouldTriggerChange.listen((_) => clearYourFormMethod());
    }
  }

  @override
  dispose() {
    super.dispose();
    streamSubscription.cancel();
  }

  void clearYourFormMethod() {
    print('Please clear your form here');
  }

  @override
  Widget build(BuildContext context) {
    return Text("FormCliente");
  }
}

class FormFinanceiro extends StatefulWidget {
  final Function buttonClicked;

  FormFinanceiro({this.buttonClicked});

  @override
  _FormFinanceiroState createState() => _FormFinanceiroState();
}

class _FormFinanceiroState extends State<FormFinanceiro> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          child: new Text("FormFinanceiro"),
          onPressed: widget.buttonClicked,
        )
      ],
    );
  }
}

答案 1 :(得分:0)

您需要抬起state

  1. _CadastrarClienteState类中创建控制器。
  2. _CadastrarClienteState中创建回调
  3. 将控制器传递给孩子FormFinanceiro
  4. 将回调传递给子FormCliente
  5. 现在,在FormCliente中修改onbuttonpressed函数,以便在按下按钮时调用回调。
  6. 最后,在_CadastrarClienteState中提供的回调方法中,使用控制器清除值。