提问者:小点点

按下按钮时颤振更新第二个父对象


我正在开发一个颤振应用程序,我想在按下按钮时更新二级家长的状态。当按下“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个答案

匿名用户

从子部件更新父部件/类的最简单方法是传递在父部件中创建的函数,然后在需要更新时从子部件调用该函数。然而,如果你需要把它传给多个孩子,那就麻烦了。通常在这种情况下,您希望您的父对象是一个StatefulWidget,并在分配新标题时创建的函数中调用setState

下一个解决方案是使用InheritedWidgets或ChangeNotifiers。

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