如何在flutter中的不同dart文件中通过不同的类发送数据

时间:2018-12-10 14:42:11

标签: dart flutter

我在编写应用程序时被打扰了

void main() {
runApp(Myapp());
}
class Myapp extends StatelessWidget {
bool s=false;

@override
Widget build(BuildContext context) {
return (MaterialApp(
    debugShowCheckedModeBanner: false,
    title: "haha app",
    theme: ThemeData(primarySwatch: Colors.lime),
    home: s ? HomeScreen(null) : LoginPage()));
}
}

上面的代码是main.dart文件的

这是我的另一个名为Login.dart的文件,代码如下所示

class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

Widget build(BuildContext context) {
return(some button ontap:(\\ on tap on this i have to change the bool s value in main.dart to true how to do that){       
}
)
}

点击按钮后,主dart文件中的s值应更改为true,但没有导航器,因为我们单击此处并不是在导航。 请帮我, 预先感谢

1 个答案:

答案 0 :(得分:2)

您可以使用回调来传达您的小部件,像这样

创建一个用于获取回调的方法,在本例中为onChangeBool,将回调传递给您的LoginPage小部件。

    class Myapp extends StatelessWidget {
    bool s=false;

    onChangeBool(){
      //change your var here 

      s = true;

      //refresh the state
         setState(() {

            });
    }

    @override
    Widget build(BuildContext context) {
    return (MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "haha app",
        theme: ThemeData(primarySwatch: Colors.lime),
        home: s ? HomeScreen(null) : LoginPage(onPressed: () => onChangeBool() ));
    }
    }

接收回叫,然后在按下按钮时调用

    class LoginPage extends StatefulWidget {

    final VoidCallback onPressed;

    LoginPage({this.onPressed});

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

    class _LoginPageState extends State<LoginPage> {

    Widget build(BuildContext context) {

        return RaisedButton(
          child: Text("button"),
          onPressed: (){
            widget.onPressed();
          },
        )

    }
    )
    }

如果要传递数据,可以使用ValueChanged回调,如果要传递复杂的数据,请使用typedef /

创建自己的回调

使用ValueChanged的示例。

    class Myapp extends StatelessWidget {
    bool s=false;

    receiveData(String data){
       print("your text here : $data");
    }

    @override
    Widget build(BuildContext context) {
    return (MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "haha app",
        theme: ThemeData(primarySwatch: Colors.lime),
        home: s ? HomeScreen(null) : LoginPage(onPressed: receiveData ));
    }
    }



    class LoginPage extends StatefulWidget {

    final ValueChanged<String> onPressed;

    LoginPage({this.onPressed});

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

    class _LoginPageState extends State<LoginPage> {

    Widget build(BuildContext context) {

        return RaisedButton(
          child: Text("button"),
          onPressed: (){
            widget.onPressed("passing this data");
          },
        )

    }
    )
    }