Flutter-如何在其他窗口小部件中访问TextEditingController?

时间:2020-07-30 21:02:42

标签: android flutter dart

我的main.dart中有一个 TextField ,带有名为 textcontroller 的控制器。 在其他小部件( button.dart )中,我有一个按钮。如果按该按钮,则应将main.dart中的 Text 小部件的文本设置为 TextField 的文本。只需执行与main.dart中的第一个按钮相同的操作即可。如何从其他小部件(文件)访问此TextEditingController?

以下是我的应用的视频,可帮助您更好地理解。 https://streamable.com/xi0dn1

这是我的main.dart完整代码

import 'button.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class MyHomePageState extends State<MyHomePage> {
  String var1 = "text1";
  TextEditingController textController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My app"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            TextField(
              controller: textController,
            ),
            RaisedButton(
              child: Text("button in the same widget"),
              onPressed: () {
                setState(() {
                  var1 = textController.text;
                });
              },
            ),
            Text(var1),
            Button2(),
          ],
        ),
      ),
    );
  }
}

这是我的button.dart代码

import 'main.dart';

class Button2 extends StatefulWidget {
  @override
  _Button2State createState() => _Button2State();
}

class _Button2State extends State<Button2> {
  String var2 = "text2";

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("button in second widget"),
            onPressed: () {
              setState(() {
                var2 = MyHomePageState().textController.text.toString();
              });
            },
          ),
          Text(var2),
        ],
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:2)

将功能与小部件分开并传递功能。

在MyHomePageState中:

// Extract the function
void onPressedFunction() {
  setState(() {
    var1 =  textController.text;
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    // ...
    child: Column(
      children: <Widget>[
        RaisedButton(
          // ...
          onPressed: onPressedFunction, // function is extracted
        ),
        Text(var1),
        Button2(onPressedFunction), // pass the function
      ],
    ),
  ); 
}

在Button2中:

class Button2 extends StatefulWidget {
  final Function onPressedFunction;

  Button2(this.onPressedFunction); // accept the function

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

class _Button2State extends State<Button2> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("button in second widget"),
            onPressed: widget.onPressedFunction, // use the same function
          ),
          Text(var2),
        ],
      ),
    );
  }
}

这样,您的Button2将执行与按下时的第一个按钮相同的操作。

答案 1 :(得分:1)

您可以将GlobalKey类型的MyHomePageState用于MyHomePage,并将其传递给button2的构造函数。使用GlobalKey,您可以在相应小部件的状态上调用方法。

main.dart

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final GlobalKey<MyHomePageState> key = new GlobalKey(); // this is new
  final String title;

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

class MyHomePageState extends State<MyHomePage> {
  String var1 = "text1";
  TextEditingController textController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
  }
  
  getText() { // this is new
    return textController.text; 
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My app"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            TextField(
              controller: textController,
            ),
            RaisedButton(
              child: Text("button in the same widget"),
              onPressed: () {
                setState(() {
                  var1 = textController.text;
                });
              },
            ),
            Text(var1),
            Button2(widget.key), // this has changed
          ],
        ),
      ),
    );
  }
}

button2.dart

import 'package:flutter/material.dart';
import 'main.dart';
class Button2 extends StatefulWidget {
  final GlobalKey<MyHomePageState> homeKey; // this is new
  Button2(this.homeKey); // this is new
  @override
  _Button2State createState() => _Button2State();
}

class _Button2State extends State<Button2> {
  String var2 = "text2";

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("button in second widget"),
            onPressed: () {
              setState(() {
                var2 = widget.homeKey.currentState.getText(); // this is new
              });
            },
          ),
          Text(var2),
        ],
      ),
    );
  }
}