Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

dart - call method in one stateful widget from another stateful widget - Flutter

I have a flutter project that I am working on I can't put the whole code cause its more than 500 lines of code so I will try to ask my question as simply as I acn using the imp. section of the code .

I am having a stateful widget and having some functions inside that stateful widget under the class that extends State<MusicPlayer>

file libmain.dart

just take a simple function like

class MyAppState extends State<MyApp>{
...
void printSample (){
  print("Sample text");
}
...

this function is inside the stateful widget inside main class .

there is another file libMyApplication.dart

this file also has a stateful widget can I do something so that I can call the function printSample() here ..

class MyApplicationState extends State<MyApplication>{
...
@override
  Widget build(BuildContext context) {
    return new FlatButton(
      child: new Text("Print Sample Text"),
      onPressed :(){
       // i want to cal the function here how is it possible to call the 
       // function 
       // printSample()  from here??  
      }
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To call a function of a parent, you can use the callback pattern. In this example, a function (onColorSelected) is passed to the child. The child calls the function when a button is pressed:

import 'package:flutter/material.dart';

class Parent extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ParentState();
  }
}

class ParentState extends State<Parent> {
  Color selectedColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          color: selectedColor,
          height: 200.0,
        ),
        ColorPicker(
          onColorSelect: (Color color) {
            setState(() {
              selectedColor = color;
            });
          },
        )
      ],
    );
  }
}

class ColorPicker extends StatelessWidget {
  const ColorPicker({this.onColorSelect});

  final ColorCallback onColorSelect;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        RaisedButton(
          child: Text('red'),
          color: Colors.red,
          onPressed: () {
            onColorSelect(Colors.red);
          },
        ),
        RaisedButton(
          child: Text('green'),
          color: Colors.green,
          onPressed: () {
            onColorSelect(Colors.green);
          },
        ),
        RaisedButton(
          child: Text('blue'),
          color: Colors.blue,
          onPressed: () {
            onColorSelect(Colors.blue);
          },
        )
      ],
    );
  }
}

typedef ColorCallback = void Function(Color color);

Internal Flutter widgets like buttons or form fields use exactly the same pattern. If you only want to call a function without any arguments, you can use the VoidCallback type instead defining your own callback type.


If you want to notify a higher up parent, you can just repeat this pattern on every hierarchy level:

class ColorPickerWrapper extends StatelessWidget {
  const ColorPickerWrapper({this.onColorSelect});

  final ColorCallback onColorSelect;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(20.0),
      child: ColorPicker(onColorSelect: onColorSelect),
    )
  }
}

Calling a method of child widget from a parent widget is discouraged in Flutter. Instead, Flutter encourages you to pass down the state of a child as constructor parameters. Instead of calling a method of the child, you just call setState in the parent widget to update its children.


One alternative approach are the controller classes in Flutter (ScrollController, AnimationController, ...). These are also passed to the children as constructor parameters, and they contain methods to control the state of the child without calling setState on the parent. Example:

scrollController.animateTo(200.0, duration: Duration(seconds: 1), curve: Curves.easeInOut);

The children are then required to listen to these changes to update their internal state. Of course, you can also implement your own controller class. If you need to, I recommend you to look at the source code of Flutter to understand how that works.


Futures and streams are another alternative to pass down state, and could also be used to call a function of a child.

But I really don't recommend it. If you need to call a method of a child widget, it is very like that your application architecture is flawed. Try to move the state up to the common ancestor!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...