Flutter-在子孙中调用setState后重建父对象

时间:2019-12-13 21:05:37

标签: android flutter dart

我有一类带有主页,另一类带有Dialog(当用户单击浮动按钮时显示)。

主页上有一个TextField,我想从对话框的下拉菜单中选择某些东西后立即更新(该菜单与TextField距离很远,在另一个类中)。我如何告诉Flutter重建该(父)类?

它对我不起作用,在您编写完应用更改后,我的下拉菜单中没有选项,并且无法点击。

render() {
    const product = this.state.products.sort(() => Math.random() - Math.random()).slice(0, 1);
    return (
        <article className="rand-product-cont">
            {product && product.map((product, index) => (
            <article key={index} className="rand-product">
                <h3>"{product.name}"</h3>
            </article>
            ))}
        </article>
    );
};

2 个答案:

答案 0 :(得分:2)

Jacek,不确定您尝试过什么,但是一种实现所需目标的方法是使用Navigator.push的对话框选择。这是一个简单的例子,

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  String text = 'Original text';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: Text('Test'),),
            body: Center(
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                          Padding(
                              padding: const EdgeInsets.only(
                                  left: 10.0, right: 10.0),
                              child: Column(children: <Widget>[
                                Text(text, style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
                              ]))
                        ])),
          floatingActionButton: Builder( builder: (context) => FloatingActionButton(
            child: Icon(Icons.refresh),
            onPressed: () async {
              update(context);
            },
          )),
        ),
    );
  }

  update(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => Dialog()),
    );

    setState(() {
      text= result;
    });
  }
}

class Dialog extends StatelessWidget {
  String dropdownValue = 'Updated item 1';
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
            title: new Text('Test dialog'),
            content: 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) {
                Navigator.pop(context, newValue);
              },
              items: <String>[
                'Updated item 1',
                'Updated item 2',
                'Updated item 3',
                'Updated item 4'
              ].map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            ),
            actions: <Widget>[
              // usually buttons at the bottom of the dialog
              new FlatButton(
                child: new Text('Cancel'),
                onPressed: () {
                  Navigator.pop(context, true);
                },
              )
            ],
          );
  }
}

demo

希望这堆麻木。

答案 1 :(得分:1)

此用例需要两件事

  1. ValueNotifier<String>:仅在选择值时更新Text小部件。
  2. showDialog<String>:返回字符串值的对话框。

使用ValueNotifier将非常有效,因为您可以定位Text小部件,并且仅在值更改时重新构建它。这将避免不必要地在屏幕上重建一些不使用此值的任意窗口小部件。

以下是工作代码供您参考: Run on DartPad

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AppContent(),
    );
  }
}

class AppContent extends StatelessWidget {
  final ValueNotifier<String> _textValue = ValueNotifier<String>('Default Text');
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Demo',),),
        body: ChildWidget(_textValue),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            showDialog<String>(
                context: context,
                builder: (BuildContext dialogContext) {
                  return Dialog(
                    onValuePicked: (String value) {
                      Navigator.pop(context, value);
                    },
                  );
                }).then((String value) {
              if (value != null && value.isNotEmpty) {
                _textValue.value = value;
              }
            });
          },
        ),
      );
  }
}

class ChildWidget extends StatelessWidget {
  final ValueNotifier<String> textValue;
  ChildWidget(this.textValue);

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      builder: (BuildContext context, value, Widget child) {
        return Text(value,  style: Theme.of(context).textTheme.display2,);
      },
      valueListenable: textValue,
    );
  }
}

class Dialog extends StatelessWidget {
  final ValueChanged<String> onValuePicked;
  static const List<String> items = <String>[
    'item 1',
    'item 2',
    'item 3',
    'item 4'
  ];
  static String dropdownValue = items[0];

  Dialog({Key key, this.onValuePicked}) : super(key: key);

  @override
  Widget build(BuildContext context) => AlertDialog(
        title: new Text('Item picker'),
        content: DropdownButton<String>(
          value: dropdownValue,
          onChanged: onValuePicked,
          items: items.map<DropdownMenuItem<String>>(
            (String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            },
          ).toList(),
        ),
      );
}

enter image description here