无法将数据传递给构造函数(颤振)

时间:2019-07-11 21:54:53

标签: flutter dart

我试图将列表传递给有状态的小部件的构造函数,但是当在main.dart中添加小部件时,它不需要任何参数。


class Appointments extends StatefulWidget {

  List clients;

  Appointments({Key key, this.clients}): super(key: key);

  @override
  State<StatefulWidget> createState() {
    return AppointmentState();
  }
}

class AppointmentState extends State<Appointments> {
  @override
  Widget build (BuildContext context) {
    return Container(
      child: Expanded(
        child: ListView.builder(
          itemCount: widget.clients.length,
          itemBuilder: (context, index) {...

在main.dart中添加Appointments()

class MyAppState extends State<MyApp> {
  List _clients = ["James Doe", "Beth Oliver", "Martha Dixon", "Peter Kay"];

  @override
  Widget build (BuildContext context) {
    return MaterialApp(
      title: "MyApp",
      home: Scaffold (
        appBar: AppBar(
          title: Text("Your Appointments")
        ),
        body: Column(
          children: [
            Align(
              alignment: AlignmentDirectional.center,
              child: Text("Your Appointments"),
            ),
            Appointments()...

1 个答案:

答案 0 :(得分:1)

如果您的Appointments小部件需要一个非空的客户端列表,请将其作为构造函数中的必需参数:

Appointments({Key key, @required this.clients}): super(key: key);

然后在main.dart中这样称呼它:

Appointments(clients: _clients),