在小部件树Flutter中检测到重复的GlobalKey

时间:2019-12-23 05:11:20

标签: android ios flutter

我有一个列表视图,其中有一张卡片作为列表视图的子级。该卡包含带有表单键的TextFormField。由于它是一个列表视图,因此它使用相同的表单密钥多次构建卡,因此出现错误:

Duplicate GlobalKey detected in widget tree.

请帮助我。

这是我的代码。

  final GlobalKey<FormState> _formKey =
  new GlobalKey<FormState>(debugLabel: ' _formKey');

 @override
 Widget build(BuildContext context) {

return  Card(
    margin: EdgeInsets.symmetric(
      horizontal: 15,
      vertical: 4,
    ),
    child: Padding(
      padding: EdgeInsets.all(8),
      child: Column(
        children: <Widget>[
          ListTile(
            leading: CircleAvatar(
              backgroundColor: Colors.blue,
              child: Padding(
                padding: EdgeInsets.all(5),
                child: FittedBox(
                  child: Text(
                    widget.price,
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ),
            title: Text('Title'),
            subtitle: Text('Subtitle'),
            trailing: Text(widget.quantity.toString() + ' x'),
          ),

          Padding(
              padding: const EdgeInsets.only(
                  left: 32, right: 5, top: 0, bottom: 5),
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    new Form(
                      key: this._formKey,
                      child: new TextFormField(
                        decoration: new InputDecoration(
                            hintText: 'Add your comments',
                            labelText: 'Comments'),
                        // validator: this._validateEmail,
                        onSaved: (String value) {
                          //  _formKey.currentState.save();

                        },
                      ),
                    ),

                  ],
                ),

              ))

  }

1 个答案:

答案 0 :(得分:1)

您可以在下面复制粘贴运行完整的测试代码
您可以使用List<GlobalKey<FormState>>并通过数据列表长度生成密钥
代码段

  List<GlobalKey<FormState>> _formKey = [];
  ...
  @override
  void initState() {
    // TODO: implement initState
    _formKey = new List<GlobalKey<FormState>>.generate(dataList.length,
        (i) => new GlobalKey<FormState>(debugLabel: ' _formKey'));
    super.initState();
  }
  ...
  new Form(
            key: this._formKey[index],

工作演示

enter image description here

完整的测试代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: AppBarTheme(color: Colors.green),
        primarySwatch: Colors.purple,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class Data {
  String price;
  int quantity;
  Data({this.price, this.quantity});
}

class _MyHomePageState extends State<MyHomePage> {
  List<Data> dataList = [
    Data(price: "1", quantity: 2),
    Data(price: "3", quantity: 4)
  ];
  List<GlobalKey<FormState>> _formKey = [];

  @override
  void initState() {
    // TODO: implement initState
    _formKey = new List<GlobalKey<FormState>>.generate(dataList.length,
        (i) => new GlobalKey<FormState>(debugLabel: ' _formKey'));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: AppBar(
          title: Text('Simple Card view'),
        ),
        body: new ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              return Card(
                  margin: EdgeInsets.symmetric(
                    horizontal: 15,
                    vertical: 4,
                  ),
                  child: Padding(
                      padding: EdgeInsets.all(8),
                      child: Column(children: <Widget>[
                        ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Colors.blue,
                            child: Padding(
                              padding: EdgeInsets.all(5),
                              child: FittedBox(
                                child: Text(
                                  dataList[index].price,
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                          ),
                          title: Text('Title'),
                          subtitle: Text('Subtitle'),
                          trailing:
                              Text(dataList[index].quantity.toString() + ' x'),
                        ),
                        Padding(
                            padding: const EdgeInsets.only(
                                left: 32, right: 5, top: 0, bottom: 5),
                            child: Container(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  new Form(
                                    key: this._formKey[index],
                                    child: new TextFormField(
                                      decoration: new InputDecoration(
                                          hintText: 'Add your comments',
                                          labelText: 'Comments'),
                                      // validator: this._validateEmail,
                                      onSaved: (String value) {
                                        //  _formKey.currentState.save();
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ))
                      ])));
            }));
  }
}