flutter 如何从BuildWidget中获取密钥

wtlkbnrh  于 2023-01-14  发布在  Flutter
关注(0)|答案(1)|浏览(119)

我想获取包含在Widget build()中的值键,但它显示为“未定义”。另外,我需要将此值获取到另一个类。我该如何做?
我试过只取这个值,但它说未定义错误

String newValue = s; // It says Undefined

我也尝试过将这个值传递给另一个类,但是这个方法给出了更多的错误:c

myCard c = myCard();
String classValue = c.s; // It says 'Only static members can be accessed in initializers' and 'The getter 's' isn`t defined for the class 'myCard' '

这是main.dart文件的一部分

class MyCard extends StatefulWidget {
      @override
      myCard createState() => myCard();
    }

    class myCard extends State<MyCard> {
      int myCount = count - 1;

      void click() {
        setState(() {
          print(titlecard);
          Navigator.push(context, MaterialPageRoute(
              builder: (context) => setNewText())
          );
        });

      }

      @override
      Widget build(BuildContext context) {
        Key s = Key(myCount.toString()); // I want to get this value
        return Center(
          key: s,
          child: Card(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                  ListTile(
                  leading: Icon(Icons.album),
                  title: Text(titlecard[int.parse(s)]),
                  subtitle: Text(textcard),
                ),
                ButtonTheme.bar( // make buttons use the appropriate styles for cards
                  child: ButtonBar(
                    children: <Widget>[
                      FlatButton(
                        child: const Text('Change Text'),
                        onPressed: click,
                      ),
                      FlatButton(
                        child: const Text('LISTEN'),
                        onPressed: () {
                          print(s);
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      }

    }

    class setNewText extends StatefulWidget {
      @override
      SetNewText createState() => SetNewText();
    }

    class SetNewText extends State<setNewText> {
      myCard c = myCard();
      HomePageState s = HomePageState();
      String v = c.s; // To here
      final titleController = TextEditingController();
      final textController = TextEditingController();
      final formkey = GlobalKey<FormState>();
      List<String> titles = [''];
      void _submit() {
        setState(() {
          if (formkey.currentState.validate()) {
            formkey.currentState.save();
            Navigator.pop(context);
            titlecard.removeAt(count-s.myCount);
            titlecard.insert(count-s.myCount, titleController.text);
            textcard = textController.text;

          }
        });

      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text('Change Title'),
            ),
            body: Column(
              children: <Widget>[
                Card(
                  child: Padding(
                    padding: EdgeInsets.all(2.0),
                    child: Form(
                      key: formkey,
                      child: Column(
                        children: <Widget>[
                          TextFormField(
                            controller: titleController,
                            decoration: InputDecoration(
                                labelText: 'Title'
                            ),
                            validator: (value) => value.length < 1 ? 'Invalid Title' : null,
                            onSaved: (value) => value = titleController.text,
                          ),
                          TextFormField(
                            controller: textController,
                            decoration: InputDecoration(
                                labelText: 'Text'
                            ),
                            validator: (text) => text.length < 1 ? 'Invalid Text' : null,
                            onSaved: (text) => text = textController.text,
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                FlatButton(
                  textColor: Colors.deepPurple,
                  child: Text('SUBMIT'),
                  onPressed: _submit,
                ),
              ],
            )
        );
      }

    }
mhd8tkvw

mhd8tkvw1#

因为你只是在监听值,一种方法是使用流来监听值。你可以初始化类,在那里值可以被流式传输,并在任何地方访问它。请注意,一旦流被关闭,你只能创建一个新的流。
这是一个样本。

import 'dart:async';

import 'package:flutter/material.dart';

class SampleStream extends StatefulWidget {
  const SampleStream({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<SampleStream> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<SampleStream> {
  Counter counter = Counter();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(
        stream: counter.showCount,
        builder: (context, AsyncSnapshot<int> snapshot) {
          int count = snapshot.hasData ? snapshot.data! : 0;
          return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: Center(
              child: Text(
                  'You clicked the button $count times'),
            ),
            floatingActionButton: FloatingActionButton(
              child: const Icon(Icons.plus_one),
              onPressed: () {
                counter.setCount(++count);
              },
            ),
          );
        });
  }

  @override
  void dispose() {
    super.dispose();
    counter.disposeCount();
  }
}

class Counter {
  final _count = StreamController<int>.broadcast();
  Stream<int> get showCount => _count.stream;

  setCount(int count) {
    debugPrint('Stream sink: $count');
    _count.sink.add(count);
  }

  disposeCount() {
    _count.close();
  }
}

在本演示中,Counter_MyHomePageState中初始化,只能在同一个类中访问。调用counter.setCount(int)更新流,可以使用StreamBuilder侦听流值以获取快照。

相关问题