如何解决颤振错误:找不到Getter:'widget?

时间:2021-02-21 16:10:25

标签: flutter dart widget

我正在创建有状态的 Flutter 类,如下所示:

  class Buildings extends StatefulWidget {
      const Buildings(this._auth, {Key key, this.title}) : super(key: key);
    
      final FirebaseAuth _auth;
    
      final String title;
      @override
      _BuildingsState createState() => _BuildingsState();
    }
    
    class _BuildingsState extends State<Buildings> {
    //////
    }


Even though I am following constructor and Create State Method, I am now able to see widget object in **_BuildingsState** class. I cannot access **widget** variable. then forward In would like to get widget._auth.

How can I get widget variable. Currely I am getting :

    Error: Getter not found: 'widget

Code Where I am trying to access widget:

      Navigator.of(context).push(new MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          Rooms(widget._auth, widget.existingBuilding)));
    
        Navigator.of(context).push(route);

添加完整文件以供参考:(基本上无法在子组件中获取小部件。我也没有通过incomingWidget 对象获取小部件。例如,我没有获得incomingWidget._auth widget._auth,我的意思是任何方式)

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_page/AddBuilding.dart';
import 'package:flutter_login_page/Building.dart';
import 'package:flutter_login_page/EditBuilding.dart';
import 'package:flutter_login_page/EditRoom.dart';
import 'package:flutter_login_page/Home2.dart';
import 'package:flutter_login_page/Rooms.dart';

class Buildings extends StatefulWidget {
  const Buildings(this._auth, this.existingBuilding, {Key key, this.title})
      : super(key: key);

  final FirebaseAuth _auth;
  final Building existingBuilding;

  final String title;
  @override
  _BuildingsState createState() => _BuildingsState();
}

class _BuildingsState extends State<Buildings> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Buildings'),
      ),
      //appBar: AppBar(title: Text('ListViews')),
      floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        backgroundColor: Colors.green,
        onPressed: () {
          // setState(() {
          //   // i++;
          // });
          Navigator.pushNamed(context, 'add_building_screen');
        },
      ),
      body: BodyLayout(widget._auth, widget.existingBuilding),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.help),
            label: 'Help',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.logout),
            label: 'Logout',
          ),
        ],
        currentIndex: 0,
        selectedItemColor: Colors.amber[800],
        onTap: (value) {
          // FirebaseAuth.
          // Firebase
          if (value == 0) {
            print(value);
            print("** loading home");
            Navigator.of(context).push(
              new MaterialPageRoute(
                  builder: (BuildContext context) =>
                      new HomePageScreen("Landge Rent Manager", widget._auth)),
            );
          }
          if (value == 1) {
            print(value);
            print("** help");
            widget._auth.signOut();
          }

          if (value == 2) {
            print(value);
            print("** logging out");
            widget._auth.signOut();
            Navigator.pushNamed(context, 'login_screen');
          }
        },
      ),
    );
  }
}

class BodyLayout extends StatefulWidget {
  //FirebaseFirestore _firestore = FirebaseFirestore.instance;
  final FirebaseAuth _auth;
  final Building existingBuilding;

  const BodyLayout(this._auth, this.existingBuilding, {Key key})
      : super(key: key);

  @override
  _BodyLayoutState createState() => _BodyLayoutState();
}

class _BodyLayoutState extends State<BodyLayout> {
  @override
  Widget build(BuildContext context) {
    return _myListView(context, widget);
  }
}

void deleteBuilding(Building building) async {
  print(">>> id for deleteis " + building.id.toString());
  try {
    final existingDoc = FirebaseFirestore.instance
        .collection("Buildings")
        .doc(building.id.toString());
    return await existingDoc.set({
      'name': "${building.name}",
      'address': "${building.address}",
      "isActive": false
    });
  } on Exception catch (e) {
    print(e);
  }
}

// replace this function with the code in the examples
Widget _myListView(BuildContext context, Widget incomingWidget) {
  return StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('Buildings')
          .where("isActive", isEqualTo: true)
          .snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Container(child: Center(child: Text("No data")));
        } else {
          final buildings = snapshot.data.docs;
          return ListView.builder(
            itemCount: buildings.length,
            itemBuilder: (context, index) {
              return Card(
                //                           <-- Card widget
                child: ListTile(
                  leading: Icon(Icons.home),
                  title: Text(buildings[index].data()["name"] != null
                      ? buildings[index].data()["name"]
                      : "-"),
                  subtitle: Column(
                    children: <Widget>[
                      Container(
                          child: Row(
                        children: <Widget>[
                          FlatButton(
                            child: Text("View Rooms"),
                            onPressed: () {
                              var id = buildings[index].reference.id != null
                                  ? buildings[index].reference.id
                                  : "";
                              var name = buildings[index].data()["name"] != null
                                  ? buildings[index].data()["name"]
                                  : "";

                              var address =
                                  buildings[index].data()["address"] != null
                                      ? buildings[index].data()["address"]
                                      : "";

                              Building currentBuilding =
                                  new Building(id, name, "", address);

                              Navigator.of(context).push(new MaterialPageRoute(
                                  builder: (BuildContext context) => new Rooms(
                                      incomingWidget._auth,
                                      incomingWidget.existingBuilding)));
                            },
                          ),
                          FlatButton(
                            child: Text("Edit"),
                            onPressed: () {
                              var id = buildings[index].reference.id != null
                                  ? buildings[index].reference.id
                                  : "";
                              var name = buildings[index].data()["name"] != null
                                  ? buildings[index].data()["name"]
                                  : "";

                              var address =
                                  buildings[index].data()["address"] != null
                                      ? buildings[index].data()["address"]
                                      : "";

                              Building currentBuilding =
                                  new Building(id, name, "", address);
                              var route = new MaterialPageRoute(
                                builder: (BuildContext context) =>
                                    new EditBuilding(
                                        widget._auth, widget.existingBuilding),
                              );

                              Navigator.of(context).push(new MaterialPageRoute(
                                  builder: (BuildContext context) => Rooms(
                                      widget._auth, widget.existingBuilding)));

                              Navigator.of(context).push(route);
                              // Navigator.pushNamed(
                              //     context, 'edit_building_screen');
                            },
                          ),
                          FlatButton(
                            child: Text("Delete"),
                            onPressed: () {
                              var id = buildings[index].reference.id != null
                                  ? buildings[index].reference.id
                                  : "";
                              var name = buildings[index].data()["name"] != null
                                  ? buildings[index].data()["name"]
                                  : "";

                              var address =
                                  buildings[index].data()["address"] != null
                                      ? buildings[index].data()["address"]
                                      : "";

                              Building currentBuilding =
                                  new Building(id, name, "", address);

                              deleteBuilding(currentBuilding);
                            },
                          ),
                        ],
                      ))
                    ],
                  ),
                  onTap: () {
                    Navigator.pushNamed(context, 'rooms_screen');
                  },
                ),
              );
            },
          );
        }
      });
}

0 个答案:

没有答案