标题基本上说明了一切。一个非常nooby的问题…我有以下基本代码来创建我的应用的初始状态:
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Some title'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar(title: new Text(config.title)), body: new Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new InputWidget(), ] ), ); } }
现在,当用户单击按钮时,如何渲染新的窗口小部件?假设我要实例化另一个InputWidget。
谢谢
希望我能正确理解您的问题…
我认为要点是,您不应该想到“另一个”小部件-如果更改MyHomePage第一个孩子然后两个孩子的内容,则您实际上并没有 保留 第一个孩子,然后 添加了另一个 孩子。您只需简单地说“我想要一个孩子”,然后您改变主意并说“我想要两个孩子”。
MyHomePage
在代码中,您可以通过调用setStateinside来实现_MyHomePageState。Flutter负责保留第一个孩子并添加第二个孩子。
setState
_MyHomePageState
import 'dart:core'; import 'package:flutter/material.dart'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Some title'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int count = 1; @override Widget build(BuildContext context) { List<Widget> children = new List.generate(count, (int i) => new InputWidget(i)); return new Scaffold( appBar: new AppBar(title: new Text(widget.title)), body: new Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: children ), floatingActionButton: new FloatingActionButton( child: new Icon(Icons.add), onPressed: () { setState(() { count = count + 1; }); }, ) ); } } class InputWidget extends StatelessWidget { final int index; InputWidget(this.index); @override Widget build(BuildContext context) { return new Text("InputWidget: " + index.toString()); } }
这是你的意思吗?