【问题标题】:Access values in flutter在颤振中访问值
【发布时间】:2021-08-19 12:04:08
【问题描述】:

如何将变量值从一个有状态小部件类访问到另一个有状态小部件类。两个小部件类也位于不同的 .dart 文件中。

这是具有变量“列表点”的 screen.dart。我想在 home.dart 中使用它。

class Draw extends StatefulWidget {
  const Draw({Key? key}) : super(key: key);

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

class _DrawState extends State<Draw> {
  List points = [];
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (DragUpdateDetails details) {
        Offset localPos = details.localPosition;
        setState(() {
          if (localPos.dx >= 0 &&
              localPos.dx <= MediaQuery.of(context).size.width * 0.8 &&
              localPos.dy >= 0 &&
              localPos.dy <= MediaQuery.of(context).size.height * 0.5)
            points.add(localPos);
          else {
            points.add(null);
          }
        });
      },
      onPanEnd: (DragEndDetails details) {
        points.add(null);
      },
      child: CustomPaint(
        painter: Painter(points: points),
      ),
    );
  }
}
...rest of code

这是 home.dart

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

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

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.yellowAccent,
        onPressed: () {
          setState(() {
            
          });
        },
        child: Icon(
          Icons.restore_page,
          color: Colors.black,
        ),
      ),
      backgroundColor: Colors.grey[300],
      appBar: AppBar(
        backgroundColor: Colors.yellowAccent,
        title: Text(
          "Digit Recognizer",
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              height: 15,
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.5,
              width: MediaQuery.of(context).size.width * 0.8,
              decoration: BoxDecoration(
                  color: Colors.white, border: Border.all(color: Colors.black)),
              child: Draw(),
            ),
...rest of code

我想从 home.dart 中的 floatingActionButton 的 on press() 函数中的 screen.dart 变量中访问“点”。

【问题讨论】:

  • 您能展示一下您是如何在这两个小部件之间导航的吗?请提供一些代码,以便我们了解您的导航方式以及变量是静态的还是动态的
  • 如果您是 Flutter 新手,请参考此视频 ==> youtu.be/l3KnuUmlr-w。这将消除您的所有疑虑。
  • 你能提供一些代码吗?
  • @SiddharthAgrawal 我添加了代码。
  • @UrDistraction 这是代码。

标签: flutter dart


【解决方案1】:

您可以将这两个小部件放在同一个文件中,然后将点创建为全局变量,所以

List points = [];

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

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

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.yellowAccent,
        onPressed: () {
          setState(() {
            print(points);
          });
        },
        child: Icon(
          Icons.restore_page,
          color: Colors.black,
        ),
      ),
      backgroundColor: Colors.grey[300],
      appBar: AppBar(
        backgroundColor: Colors.yellowAccent,
        title: Text(
          "Digit Recognizer",
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              height: 15,
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.5,
              width: MediaQuery.of(context).size.width * 0.8,
              decoration: BoxDecoration(
                  color: Colors.white, border: Border.all(color: Colors.black)),
              child: Draw(),
            ),
...rest of code


class Draw extends StatefulWidget {
  const Draw({Key? key}) : super(key: key);

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

class _DrawState extends State<Draw> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (DragUpdateDetails details) {
        Offset localPos = details.localPosition;
        setState(() {
          if (localPos.dx >= 0 &&
              localPos.dx <= MediaQuery.of(context).size.width * 0.8 &&
              localPos.dy >= 0 &&
              localPos.dy <= MediaQuery.of(context).size.height * 0.5)
            points.add(localPos);
          else {
            points.add(null);
          }
        });
      },
      onPanEnd: (DragEndDetails details) {
        points.add(null);
      },
      child: CustomPaint(
        painter: Painter(points: points),
      ),
    );
  }
}
...rest of code

通常我什至不会为这种情况创建一个不同的 statefulw idget,但我猜你这样做是出于其他原因。创建一个全局变量允许从任何地方访问它\

实现第一个答案的更好方法可能是这样,但您必须看看它是否有效。

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

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

class _HomeState extends State<Home> {
  Widget drawWidget = Container();
   
  @override
  void initState(){
    super.initState();
    drawWidget = Draw();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.yellowAccent,
        onPressed: () {
          setState(() {
            print(drawWidget.points);
          });
        },
        child: Icon(
          Icons.restore_page,
          color: Colors.black,
        ),
      ),
      backgroundColor: Colors.grey[300],
      appBar: AppBar(
        backgroundColor: Colors.yellowAccent,
        title: Text(
          "Digit Recognizer",
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              height: 15,
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.5,
              width: MediaQuery.of(context).size.width * 0.8,
              decoration: BoxDecoration(
                  color: Colors.white, border: Border.all(color: Colors.black)),
              child: drawWidget,
            ),
...rest of code

在drawWidget中

class Draw extends StatefulWidget {
  const Draw({Key? key}) : super(key: key);
  List points = [];
  @override
  _DrawState createState() => _DrawState();
}

class _DrawState extends State<Draw> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (DragUpdateDetails details) {
        Offset localPos = details.localPosition;
        setState(() {
          if (localPos.dx >= 0 &&
              localPos.dx <= MediaQuery.of(context).size.width * 0.8 &&
              localPos.dy >= 0 &&
              localPos.dy <= MediaQuery.of(context).size.height * 0.5)
            widget.points.add(localPos);
          else {
            widget.points.add(null);
          }
        });
      },
      onPanEnd: (DragEndDetails details) {
        widget.points.add(null);
      },
      child: CustomPaint(
        painter: Painter(points: widget.points),
      ),
    );
  }
}
...rest of code

希望对你有帮助
每个代码中的 print 语句显示了如何访问

【讨论】:

    【解决方案2】:
    class stful1{
      //create state method
    }
    class stful1 extends state{
       //Widget build method
       //data is actual data you want to send
       Navigator.push(context,MaterialPageRoute((context)=>stful2(data)))
    }
    
    
    //stful2
    class stful2{
      //accept data in constructor
      dataType data;
      stful2(this.data);
      //create state method
    }
    class stful2 extends state{
       //Widget build method
      //access like widget.data
    }
    

    【讨论】:

    • 从代码中可以看出,他的实现非常不同,因为他在另一个内部显示有状态的小部件
    • 在我评论示例代码时,他没有提供他的实际代码。
    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2020-01-10
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多