将参数从子级传递到父级,反之亦然

时间:2020-06-01 06:30:30

标签: flutter flutter-layout

我想创建一个StatefulWidget,以便孩子可以使用parent的参数,也可以更改它。

//需要以下问题的解决方案。

import "flutter/material.dart";    
Toggle(
  builder: (value) => IconButton(
    icon: Icon(value ? Icons.add : Icons.minimize),
      onPressed: () => value = !value,
  ),
);

class Toggle extends StatefulWidget{
  final bool status;
  Widget Function(bool status) builder;
  Toggle({Key key, this.status = true, this.builder,}) : super(key: key);
  @override _ToggleState createState() => _ToggleState();
}

class _ToggleState extends State<Toggle> {
  @override Widget build(BuildContext context) => widget.builder(widget.status);
}

1 个答案:

答案 0 :(得分:0)

通常,您在父级小部件中创建一个函数来更改父级状态,然后将该函数作为道具传递给其子级小部件,以便子级可以执行它并改变父级状态。

以下是示例代码段和CodePen网址:

摘要

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('demo')
        ),
        body: Center(
          child: Parent()
        )
      )
    ),
  );
}

class Parent extends StatefulWidget{
  _ParentState createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  String _value = 'Hello';

  // This function will be passed down to the Child widget.
  void appendLetter(String letter) {
    setState(() {
      this._value += letter;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('Parent: ' + this._value),
        new Child(
          param: this._value,
          callback: this.appendLetter // passing a function as a parameter
        )
      ]
    );
  }
}

class Child extends StatefulWidget{
  final String param;
  final void Function(String) callback;

  Child({
    Key key,
    this.param,
    this.callback,
  }) : super(key: key);

  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Child: ' + widget.param),
        FlatButton(
          child: Text('Press Me'),
          onPressed: () => widget.callback('o') // invoking the function
        )
      ]
    );
  }
}

CodePen

https://codepen.io/KenyoTheDeveloper/pen/xxZxdXg