I have followed as best I can this question: Adding new ListTile item on click
尽管它不一定具有可复制性,但我创建了可以编译但不能按预期运行的文件:
import 'package:flutter/material.dart';
void main() => runApp(SeedBank());
class SeedBank extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.lightGreen,
),
home: Seeds(),
);
}
}
class Seeds extends StatefulWidget {
@override
SeedsState createState() => SeedsState();
}
class SeedsState extends State<Seeds> {
var _seedSection = List<Widget>();
Card seedSectionMethod(String title, String subtitle) {
return new Card(
child: ListTile(
title: Text(
title,
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(subtitle),
trailing: Icon(Icons.more_vert)),
);
}
void initState() {
super.initState();
_seedSection.add(
seedSectionMethod("Leek", "Bulgaarse Reuzen - Lincoln"),
);
_seedSection.add(
seedSectionMethod("Kale", "Jardin mix"),
);
_seedSection.add(
seedSectionMethod("Sunflower", "Helianthus Red"),
);
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Seed Bank'),
),
body: ListView(
children: this._seedSection,
),
floatingActionButton: FloatingActionButton(
child: Text("+"),
onPressed: () {
setState(() {
_seedSection.add(
seedSectionMethod("New Seed", "With notes"),
);
});
},
backgroundColor: Colors.lightGreenAccent,
),
);
}
}
所需的行为是:
- on app startup, that the three 'cards' with the seeds are populated.
- on button press, a new 'card' is added with the values
"new Seed"
and"with notes"
.
我希望我错过了一些有关设置状态的基本知识(仅从昨天开始),但是我对下一步该去哪里了解更多。
尝试添加以下内容:
Since
_seedSection
is modified, you have to useListView.builder
Moreover, it is better to store in state only the values and make the widget inside
itemBuilder
.