【问题标题】:Closure call with mismatched arguments: function '[]' in flutter参数不匹配的闭包调用:颤振中的函数'[]'
【发布时间】:2020-10-03 16:11:30
【问题描述】:

** 我收到此错误**

Closure call with mismatched arguments: function '[]'
Receiver: Closure: (dynamic) => dynamic from Function 'get':.
Tried calling: []("url")
Found: [](dynamic) => dynamic

我从 Firestore 接收数据的代码是这样的..

import 'package:flutter/material.dart';
import 'package:riyazat_quiz/services/database.dart';
import 'package:riyazat_quiz/views/create_quiz.dart';
import 'package:riyazat_quiz/widgets/widgets.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Stream quizStream;
  DatabaseService databaseService = DatabaseService(); // this is to call the getQuizData()  async{
return await  FirebaseFirestore.instance.collection("Quiz").snapshots();
  }


 Widget quizList(){
   return Container(
     child: StreamBuilder(
       stream:quizStream ,
       builder: (context,snapshort){
         return snapshort.data == null ? CircularProgressIndicator(): ListView.builder(
             scrollDirection: Axis.vertical,
             shrinkWrap: true,
             itemCount : snapshort.data.documents.length ,
             itemBuilder : (context,index){ return QuizTile(url:snapshort.data.documents[index].get['url'],
               title:snapshort.data.documents[index].get['title'] ,
               desc: snapshort.data.documents[index].get['desc'],);}

         );
       }
     ),
   );
 }

 @override
  void initState() {
  databaseService.getQuizData().then((val){
    setState(() {
      quizStream =val;

    });
  });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: appBar(context),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        brightness: Brightness.light,
      ),
      body:
        Column(
          children: [
            quizList(),
            FloatingActionButton(
              child: Icon(Icons.add),
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => CreateQuiz()));
              },
            ),
          ],
        ),

    );
  }
}

class QuizTile extends StatelessWidget {
  final String  url,title,desc;
  QuizTile({@required this.url,@required this.title,@required this.desc});
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          Image.network(url),
          Container(
            child: Column(
              children: [
                Text(title),
                Text(desc),
              ],
            ),
          )
        ],
      ),
    );
  }
}

谁能告诉我哪里出错了

ps:这是一个测验应用程序,我从 Firestore 获取数据, 使用流。 保存在 firestore 上的数据有“url”、“title”、“desc”三个字段。 我想在下面的小部件中检索它们并希望将它们显示在堆栈中,但是这个错误让我陷入了两者之间。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    您需要执行以下操作:

    itemCount : snapshort.data.docs.length ,
    itemBuilder : (context,index){ 
      return QuizTile(url:snapshort.data.docs[index].data()['url'],
          title:snapshort.data.docs[index].data()['title'] ,
          desc: snapshort.data.docs[index].data()['desc'],
       );
      }
    );
    

    由于您引用了一个集合,因此您需要使用docs,它将检索该集合内的文档列表:

    https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/query_snapshot.dart#L18

    然后要访问文档中的每个字段,需要调用data()

    【讨论】:

      【解决方案2】:

      @Peter Haddad 的回答是正确的。只是为了突出我自己代码中的示例的区别:

      产生相同错误的先前版本的代码:

      snapshot.data.docs[index].data["chatRoomID"]
      

      解决错误的代码更新版本:

      snapshot.data.docs[index].data()["chatRoomID"]
      

      【讨论】:

      • 除了提供更正外,您还应该描述所犯的错误,以便人们知道解决方案为何有效。
      【解决方案3】:

      更新版本:

      snapshot.data[i]['Email'],
      
      Future getRequests() async {
          QuerySnapshot snapshot = await FirebaseFirestore.instance.collection("Buyer Requests").get();
          return snapshot.docs;
        }
      
      body: FutureBuilder(
                initialData: [],
                future: getRequests(),
                builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                  indexLength = snapshot.data.length;
                  if (snapshot.hasData)
                    return SizedBox(
                      child: PageView.builder(
                        itemCount: indexLength,
                        controller: PageController(viewportFraction: 1.0),
                        onPageChanged: (int index) => setState(() => _index = index),
                        itemBuilder: (_, i) {
                          return SingleChildScrollView(
                            child: Card(
                              margin: EdgeInsets.all(10),
                              child: Wrap(
                                children: <Widget>[
                                  ListTile(
                                    leading: CircleAvatar(
                                      backgroundImage: AssetImage(
                                          'assets/images/shafiqueimg.jpeg'),
                                    ),
                                    title: Text(
                                      snapshot.data[i]['Email'],
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w700,
                                        color: Colors.black.withOpacity(0.7),
                                      ),
                                    ),
                                    subtitle: Text(
                                      snapshot.data[i]['Time'],
                                      style: TextStyle(
                                          color: Colors.black.withOpacity(0.6)),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(16.0),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.stretch,
                                      children: [
                                        Container(
                                          decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.all(Radius.circular(5)),
                                            color: Colors.grey[200],
                                          ),
                                          padding: EdgeInsets.all(10),
                                          child: Text(
                                            snapshot.data[i]['Description'],
                                            style: TextStyle(
                                                color: Colors.black.withOpacity(0.6)),
                                          ),
                                        ),
                                        SizedBox(
                                          height: 8,
                                        ),
                                        Container(
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(5)),
                                              border: Border.all(
                                                  color: Colors.grey[300])),
                                          child: ListTile(
                                            leading: Icon(Icons.category_outlined),
                                            title: Text(
                                              'Category : ${snapshot.data[i]['Category']}',
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ),
                                        ),
                                         SizedBox(height: 8),
                                        Container(
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(5)),
                                              border: Border.all(
                                                  color: Colors.grey[300])),
                                          child: ListTile(
                                            leading: Icon(Icons.location_pin),
                                            title: Text(
                                              snapshot.data[i]['Location'],
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(height: 8),
                                        Container(
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(5)),
                                              border: Border.all(
                                                  color: Colors.grey[300])),
                                          child: ListTile(
                                            leading: Icon(
                                              Icons.attach_money,
                                              color: kGreenColor,
                                            ),
                                            title: Text(
                                              'Rs.${snapshot.data[i]['Budget']}',
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: kGreenColor,
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(height: 8),
                                        Container(
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(5)),
                                              border: Border.all(
                                                  color: Colors.grey[300])),
                                          child: ListTile(
                                            leading: Icon(Icons.timer),
                                            title: Text(
                                              'Duration : ${snapshot.data[i]['Duration']}',
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                          height: 35,
                                        ),
                                        RaisedButton(
                                          padding: EdgeInsets.symmetric(vertical: 10),
                                          child: Text('Send Offer'),
                                          textColor: Colors.white,
                                          color: Colors.green,
                                          onPressed: () {
                                            // Respond to button press
                                          },
                                        ),
                                        SizedBox(
                                          height: 15,
                                        ),
                                        Center(
                                          child: Text(
                                            "${i + 1}/$indexLength",
                                            style: TextStyle(fontSize: 13),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    );
                  else
                    return Center(
                      child: Text("Null"),
                    );
                },
              ),
      

      【讨论】:

        猜你喜欢
        • 2021-01-26
        • 2021-02-22
        • 2022-12-21
        • 2013-12-01
        • 1970-01-01
        • 2022-08-13
        • 2021-12-09
        • 2021-12-10
        • 2021-09-29
        相关资源
        最近更新 更多