Matt123
Matt123

Reputation: 303

Flutter updating second parent when button is pressed

I am working on a flutter app and I want to update the second level parent's state when a button is pressed. When the "PressMe" button is pressed, I want MyHomePage's state to have Widget2's title string saved in it's own state. Can someone please help me out with this? The button is a lower level widget and I want to pass the data up two levels. Thanks!

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

Thanks!

Upvotes: 0

Views: 141

Answers (1)

SupposedlySam
SupposedlySam

Reputation: 685

The easiest way to update your parent widget/class from a child is to pass down a function you create in the parent, then call that function from your child when you need to update it. However, that gets messy if you need to pass it down through multiple children. Usually in this case you'll want your parent to be a StatefulWidget and call setState inside the function you create when you assign the new title.

The next solution is to use InheritedWidgets or ChangeNotifiers.

The ideal solution would be to use some form of state management such as Provider or Bloc.

Upvotes: 2

Related Questions