簡體   English   中英

Flutter - 在孫子中調用 setState 后重建父

[英]Flutter - Rebuild parent after calling setState in grandchildren

我有一個帶有主頁的類和另一個帶有 Dialog 的類(當用戶單擊浮動按鈕時出現)。

主頁上有一個 TextField,我想在從對話框的下拉菜單中選擇一些東西后(立即)更新(它離 TextField 很遠,在另一個類中)。 我怎么能告訴顫振重建那個(父)類?

它對我不起作用,在您編寫的應用更改后,我的下拉菜單中沒有選項並且不可點擊。

DropdownButton<double>(
   hint: Text("Specify sleep lenght"),
   value: dropdownValue,
   onChanged: onValueChange,
   items: availableLengthHours.map((l) {
     return DropdownMenuItem(
        child: new Center(child: Text(l.toString())),
        value: l,
     );
   }).toList(),
),

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);
                },
              )
            ],
          );
  }
}

演示

希望這很有效。

這個用例你需要做的兩件事

  1. ValueNotifier<String> :僅在選擇值時更新您的Text小部件。
  2. showDialog<String> :返回字符串值的對話框。

使用ValueNotifier會很有效,因為您可以定位您的 Text 小部件,並且僅在值更改時重建它。 這將避免在屏幕上不必要地重建某些不使用此值的任意 Widget。

以下是供您參考的工作代碼: 在 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(),
        ),
      );
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM