当按下按钮时颤振更新第二个父级

时间:2020-01-20 21:52:33

标签: flutter dart

我正在开发一个Flutter应用程序,我想在按下按钮时更新第二级父母的状态。当按下“ PressMe”按钮时,我希望MyHomePage的状态以其自身状态保存Widget2的标题字符串。有人可以帮我这个忙吗?该按钮是一个较低级别的小部件,我想将数据向上传递两个级别。谢谢!

//main.dart
import 'package:flutter/material.dart';
import 'Widget1.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),

        home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

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

class _MyHomePageState extends State<MyHomePage> {
String title2;
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Hello"),
      ),
      body: Center(
        child: Widget1(),
      ),
    );
  }
}
///////////////////////////////
//Widget1.dart
import 'package:flutter/material.dart';
import 'Widget2.dart';


class Widget1 extends StatefulWidget {
  _Widget1State createState() => _Widget1State();
}

class _Widget1State extends State<Widget1> {

  @override
  Widget build(BuildContext context) {
    return Widget2();
  }
}
///////////////////////////////
//Widget2.dart

import 'package:flutter/material.dart';

class Widget2 extends StatefulWidget {

  final String title = "Hello from Widget2";


  _Widget2State createState() => _Widget2State();
}

class _Widget2State extends State<Widget2> {
String title = "Hello from Widget2";


  @override
  Widget build(BuildContext context) {
    return RaisedButton(
          onPressed: null,
          child: Text(
            'PressMe',
            style: TextStyle(fontSize: 20)
          ),
        );
  }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

从子级更新父级窗口小部件/类的最简单方法是传递在父级中创建的function,然后在需要更新时从子级调用该函数。但是,如果您需要将其传递给多个子对象,那就太麻烦了。通常,在这种情况下,您希望您的父母是StatefulWidget,并在分配新标题时在创建的函数内调用setState

下一个解决方案是使用InheritedWidgetChangeNotifier s。

理想的解决方案是使用某种形式的状态管理,例如ProviderBloc