【问题标题】:Creating a new widget on User Click(Flat Button)在用户点击(平面按钮)上创建一个新的小部件
【发布时间】:2020-01-03 02:20:20
【问题描述】:

我有一个创建 Post 模型的 Post 类。我想在用户每次点击平面按钮时创建这个模型。使用 onPressed 函数解决此问题的最佳方法是什么?

这将是一个帖子,其中包含用户添加到文本字段的文本,当他们提交时,它将显示在新帖子中。

【问题讨论】:

  • 使用按钮的onPressed 属性来响应按钮被按下的动作。
  • 向我们展示您目前拥有的东西。然后我们可以以最好的方式提供帮助。

标签: flutter dart


【解决方案1】:

你可以尝试使用listview.builder,这是如何使用它的简单示例。我只是在创建新项目时编辑默认代码。

return Scaffold(
  appBar: AppBar(

    title: Text(widget.title),
  ),
  body: Center(

    child: ListView.builder(
      itemCount: _counter,
      reverse: true,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return Padding(
          padding: const EdgeInsets.all(10.0),
          child: Container(
            color: Colors.red,
            child: Center(child: Text('data $index')),
          ),
        );
      },

    )
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: Icon(Icons.add),
  ), 
);

【讨论】:

    【解决方案2】:

    基本上,您希望将项目添加到列表中,然后呈现该列表的内容。

    List<String> messages = [];
    ...
    onPressed: ()=> setState(()=>messages.add("SomeText"))
    

    然后渲染列表:

    //Can use the map() api, to convert the list of Strings into a list of widgets:
    List<Widget> children = messages.map((m) => Text(m));
    return ListView(children: children);
    
    //Or, use ListView.builder() to create the widgets on demand:
    return ListView.builder(
      itemBuilder: (context, index)=>Text(messages[index]),
      itemCount: messages.length
    )
    

    builder 方法更适合大型列表。

    【讨论】:

      【解决方案3】:

      这是一个简单的演示

      List<String> posts = [];
      
      @override
        Widget build(BuildContext context) {
            return Scaffold(body: Column(
                   children: <Widget>[
                      ListView.builder(
                         itemCount: posts.length,
                         itemBuilder: (BuildContext ctxt, int index) {
                               return new Text(posts[index]);//use any widget
                         }
                      ),
                     FloatingActionButton(
                      backgroundColor: Colors.white,
                      child: Icon(
                        Icons.close,
                        color: Colors.red,
                      ),
                      onPressed: () {
                       setState(() {
                         posts.add(newpost);//add what you want
                         });
                      },
                    ),
                   ]),
                );
          }
      

      希望对你有帮助..

      【讨论】:

        猜你喜欢
        • 2016-02-10
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 2015-10-16
        • 1970-01-01
        • 1970-01-01
        • 2020-12-10
        • 1970-01-01
        相关资源
        最近更新 更多