如何修复Flutter Dropdown中的“只能在初始化程序中访问静态成员”

时间:2019-05-20 11:18:10

标签: dart flutter

我是Flutter的新手。 我正在从flutter文档尝试此示例 https://api.flutter.dev/flutter/material/DropdownButton-class.html

Flutter Dropdown(包装在ListView小部件中)通过说``初始化器中只能访问静态成员''而给setState错误,任何人都可以帮我这个忙。提前致谢。

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';

class PurchaseOrder extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PO(),
    );
  }

}

class PO extends StatefulWidget {

  @override
  _POState createState() => new _POState();

}

class _POState extends State<PO> {

  static String dropdownValue = 'One';

  var purchasehandle = <Widget>[

      Container(
         padding: EdgeInsets.all(5.0),
         child: Card(
           child: Container(
             padding: EdgeInsets.all(10.0),
             child: Form(
               child: ListView(
                 children: <Widget>[
                   Text(
                    "Purchase No 1",
                    style: TextStyle(fontWeight: FontWeight.bold)
                   ),
                    DateTimePickerFormField(
                      inputType: InputType.date,
                      format: DateFormat("dd-MM-yyyy"),
                      editable: false,
                      decoration: InputDecoration(
                      hintText: 'Purchase Date',
                      hasFloatingPlaceholder: false
                      ),
                    ),

                    DropdownButton<String>(
                       value: dropdownValue,
                        onChanged: (String newValue) {

                          setState(() {    // Error Only static members can be accessed in initializers
                            dropdownValue = newValue; 
                          });
                        },

        items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          })
          .toList(),
      )

                   ],
               ),
             ),
           ),
         ),
      )
  ];


  @override
  Widget build(BuildContext context)
  {
     return Scaffold(
      appBar: AppBar(
          title: Text("VIX - Purchase Order"),
          backgroundColor: const Color(0xFF2C3E50)
      ),
      body: Stack(
        children: purchasehandle,
      ),
    );
  }

}

2 个答案:

答案 0 :(得分:0)

您已将dropdownValue声明为静态变量,因此应从声明中删除static或将其用作_POState.dropdownValue

您可以详细了解here

答案 1 :(得分:0)

您只需要将小部件purchasehandle的主体添加到小部件树本身,即在Stack下的body中。您无需将其声明为var。