我正在创建一个 flutter 朔迷离的应用程序。我想从Firebase提取数据并显示网格 View 。数据正在从Firebase正确获取。数据在initState()中获取,但未更新TheGridview扩展的另一个类_MyHomePageState。我正在使用一个变量
documents,用于存储Firebase中的列表。 initState()文档值,但在createchildwidget方法中,文档为空。我尝试了很多方法,请帮帮我。代码如下所示。

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:augr/location/LocationScreen.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';

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

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.

      MyApp({this.firestore});
      final Firestore firestore;


      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: MyHomePage(title: 'My Shop', firestore: firestore)
        );
      }
    }

    class MyHomePage extends StatefulWidget {

      MyHomePage({Key key, this.title, this.firestore}) : super(key: key);
      final Firestore firestore;
      final String title;

      @override
      _MyHomePageState createState() => new _MyHomePageState(firestore: firestore);
    }

    class _MyHomePageState extends State<MyHomePage> {
      _MyHomePageState({this.firestore});
      final Firestore firestore;
      var documents = [];

      void initState(){
        Firestore.instance.collection("messages").getDocuments().then((data) async{
          var list = data.documents;
          documents = list;
          print("init state document:"+documents.length.toString());  // value is getting
          super.initState();
          setState((){
            documents = list;
          });
        });



      }

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            iconTheme: IconThemeData(
              color: Colors.black, //change font color here
            ),
            backgroundColor: new Color(0xFFFAFAFA),
          )
          title:"title",
          body: TheGridview().build(),
        );
      }
    }

    class TheGridview extends _MyHomePageState{
      Card makeGridCell(String name, IconData icon){
        return Card(
          elevation: 1.0,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.min,
            verticalDirection: VerticalDirection.down,
            children: <Widget>[
              Center(child: Icon(icon)),
              Text(name)
            ],
          ),
        );
      }

      @override
      Widget build(BuildContext context) {
        return GridView.count(
          primary: true,
          padding: EdgeInsets.all(1.0),
          crossAxisCount: 2,
          childAspectRatio: 1.0,
          mainAxisSpacing: 1.0,
          crossAxisSpacing: 1.0,

          children: createchildwidget(),

          /*  children: <Widget>[
            makeGridCell("Home", Icons.access_alarm)
          ],*/


        );
      }

      List<Widget> createchildwidget(){
        print("createchildwidget:"+documents.length.toString()); // the value getting 0
        List<Widget> createchildwidget = List<Widget>();
        for(int i=0;i<documents.length;i++){
          createchildwidget.add(TheGridview().makeGridCell(makeGridCell(data[i].data['message'], Icons.access_alarm));

        }
        return createchildwidget;
      }


    }

最佳答案

不要将TheGridView当作新类,而应将其作为一个函数,并在加载document数据时调用它。
试试这个:

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:augr/location/LocationScreen.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';

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

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.

      MyApp({this.firestore});
      final Firestore firestore;


      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: MyHomePage(title: 'My Shop', firestore: firestore)
        );
      }
    }

  class _MyHomePageState extends State<MyHomePage> {
      _MyHomePageState({this.firestore});
      final Firestore firestore;
      var documents = [];
bool isDocLoaded=false;
      void initState(){
        Firestore.instance.collection("messages").getDocuments().then((data) async{
          var list = data.documents;
          documents = list;
          print("init state document:"+documents.length.toString());  // value is getting
          super.initState();
          setState((){
            isDocLoaded=true;
            documents = list;
          });
        });



      }

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            iconTheme: IconThemeData(
              color: Colors.black, //change font color here
            ),
            backgroundColor: new Color(0xFFFAFAFA),
          )
          title:"title",
          body: isDocLoaded? TheGridview():Center(child:CircularProgressIndicator()),
        );
      }

Widget TheGridView(){
return GridView.count(
          primary: true,
          padding: EdgeInsets.all(1.0),
          crossAxisCount: 2,
          childAspectRatio: 1.0,
          mainAxisSpacing: 1.0,
          crossAxisSpacing: 1.0,

          children: createchildwidget(),

          /*  children: <Widget>[
            makeGridCell("Home", Icons.access_alarm)
          ],*/
);
}

Card makeGridCell(String name, IconData icon){
        return Card(
          elevation: 1.0,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.min,
            verticalDirection: VerticalDirection.down,
            children: <Widget>[
              Center(child: Icon(icon)),
              Text(name)
            ],
          ),
        );
      }
List<Widget> createchildwidget(){
        print("createchildwidget:"+documents.length.toString()); // the value getting 0
        List<Widget> createchildwidget = List<Widget>();
        for(int i=0;i<documents.length;i++){
          createchildwidget.add(makeGridCell(makeGridCell(data[i].data['message'], Icons.access_alarm));
        }
return createchildwidget;
      }
    }

关于android - flutter initstate()列表未访问其他类小部件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53470990/

10-10 17:57