【问题标题】:Access List from statefulwidget to state从 statefulwidget 到 state 的访问列表
【发布时间】:2021-02-27 08:54:55
【问题描述】:

我想将一个列表从屏幕 1 传递到屏幕 2 statefulwidget,并想向其中添加数据。

列表类型问题,

class Question {
  String questionText;
  String answerText;

  Question({this.questionText, this.answerText});
}

我将列表传递到第二个屏幕 类 CardPage 扩展 StatefulWidget {

  final List<Question> questionBank;
  CardPage({@required this.questionBank});

  @override
  ......

我将内容从状态添加到列表中,

TextField(onChanged: (text) {question = text;}),
TextField(onChanged: (text) {answer = text;}),
FlatButton(
     child: Text("Create"),
     onPressed: () {setState(() {
                         questionBank.add(Question(questionText: question, answerText: answer));});
                   }
)

Bt 我不知道如何将有状态小部件中的列表连接到状态以访问它。我知道它有小部件,但不知道如何完全导入列表以说明它。 谁来帮帮我

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    试试这个 简单的演示。

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MaterialApp(
        home: MyApp(),
      ));
    }
    
    class MyApp extends StatefulWidget {
      @override
      _State createState() => _State();
    }
    
    class _State extends State<MyApp> {
      final List<String> names = <String>['apple', 'samsung', 'shirsh'];
    
      TextEditingController nameController = TextEditingController();
    
      void addItemToList(){
        setState(() {
          names.insert(0,nameController.text);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text('Example'),
            ),
    
            body: Column(
                children: <Widget>[
                  Row(
                    children: [
                      Expanded(
                        flex: 5,
                        child: Padding(
                          padding: EdgeInsets.all(20),
                          child: TextField(
                            controller: nameController,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              labelText: 'Contact Name',
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 2,
                        child: RaisedButton(
                          child: Text('Add Item'),
                          onPressed: () {
                            if(nameController.text.toString()!="")
                              addItemToList();
                          },
                        ),
                      )
                    ],
                  ),
    
    
                  Expanded(
                      child: ListView.builder(
                          padding: const EdgeInsets.all(8),
                          itemCount: names.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              height: 50,
                              margin: EdgeInsets.all(2),
                              color: Colors.cyan,
                              child: Center(
                                  child: Text('${names[index]}',
                                    style: TextStyle(fontSize: 18),
                                  )
                              ),
                            );
                          }
                      )
                  )
                ]
            )
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以将函数而不是列表传递给您的CardPage。创建新问题时应该调用它。我认为这是最简单的解决方案。

      你的 CardPage 应该是这样的:

      class CardPage extends StatefulWidget {
        final Function(Question) createQuestion;
      
        CardPage({Key key, @required this.createQuestion}) : super(key: key);
      
        @override
        State<StatefulWidget> createState() => _CardPageState();
      }
      
      class _CardPageState extends State<CardPage> {
        String _question = '';
        String _answer = '';
      
        @override
        Widget build(BuildContext context) {
          return Column(children: [
            TextField(onChanged: (text) {
              _question = text;
            }),
            TextField(onChanged: (text) {
              _answer = text;
            }),
            FlatButton(
                child: Text("Create"),
                onPressed: () {
                  setState(() {
                    final question =
                        Question(questionText: _question, answerText: _answer);
                    widget.createQuestion(question);
                  });
                })
          ]);
        }
      }
      

      问题列表所有者状态应该是这样的:

      class _FirstWidgetState extends State<FirstWidget> {
      
        final List<Question> questionBank = [];
      
        @override
        Widget build(BuildContext context) {
          return ...
              CardPage(createQuestion: _createQuestion);
              ...
        }
      
        void _createQuestion(Question question) {
          setState(() {
            questionBank.add(question);
          });
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 2021-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 2021-09-10
        • 1970-01-01
        • 2019-12-09
        相关资源
        最近更新 更多