简体   繁体   English

Flutter - 方法“|” 在 null 上调用。 热重载后它正在工作

[英]Flutter - The method '|' was called on null. After hot reload it is working

I am pretty new in flutter.我是 flutter 的新手。 I don't know what happening in background because after hot reload its work fine.我不知道后台发生了什么,因为热重载后它的工作正常。 On another dart files that happens, firebase dont provide me data on initialization just after hot reload.在发生的另一个 dart 文件中,firebase 在热重载后不提供初始化数据。

class CityServices {
      getCites() {
        return Firestore.instance.collection('cities').getDocuments();
      }
    }

class _HomeScreenState extends State<HomeScreen> {
  bool citiesFlag = false;
  var cities;
  int citiesCount;
  String actualCity;

Maybe mistake is here.也许错误就在这里。

  @override
  void initState() {
    super.initState();
    CityServices().getCites().then((QuerySnapshot) {
      if (QuerySnapshot.documents.isNotEmpty) {
        citiesFlag = true;
        cities = QuerySnapshot.documents;
        citiesCount = QuerySnapshot.documents.length;
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: MyColors.vintageGreen,
        appBar: AppBar(
          backgroundColor: MyColors.background,
          title: Center(
            child: Text(
              'Válasszon települést...',
              style: GoogleFonts.barlowCondensed(
                  color: MyColors.appbarText,
                  fontSize: 26.0,
                  fontWeight: FontWeight.w500),
            ),
          ),
        ),
        body: Center(
          child: Container(
            child: GridView.count(
              crossAxisCount: 2,
              children: List.generate(citiesCount, (index) {
                return Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: InkWell(
                    onTap: () {
                      actualCity = cities[index]['city_name'];
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                CityView(cityName: actualCity)),
                      );
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        ListTile(
                          title: Center(
                              child: Text(
                            cities[index]['city_name'],
                            style: TextStyle(
                                fontWeight: FontWeight.w500, fontSize: 18.0),
                          )),
                          subtitle: Center(child: Text('22 bejegyzés')),
                        ),
                        Flexible(
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                            child: Padding(
                              padding: EdgeInsets.only(bottom: 15.0),
                              child: Image(
                                image: AssetImage(
                                  cities[index]['img_path'],
                                ),
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  color: MyColors.background,
                );
              }),
            ),
          ),
        ),
      ),
    );
  }
}

Maybe here is the mistake?也许这是错误? Should it be on top of dart file?它应该在 dart 文件之上吗?

class HomeScreen extends StatefulWidget {
  static const String id = 'home';
  @override
  _HomeScreenState createState() => new _HomeScreenState();
}

Let me explain the issue and why it is happening, then propose few solutions.让我解释一下这个问题以及它发生的原因,然后提出一些解决方案。

inside initState you are calling CityServices().getCites().then... which is an async method.initState中,您正在调用CityServices().getCites().then...这是一个async方法。
However, when your widget is built for the first time, the data you expect from Firestore is not ready yet, thus you get null for both cities and citiesCount .但是,当您的小部件首次构建时,您期望从 Firestore 获得的数据还没有准备好,因此您会得到nullcitiesCount cities

Short term solution:短期解决方案:
make sure there is null check, display indicator while waiting for the data.确保有 null 检查,等待数据时显示指示灯。

body: Center(
   child: (cities == null) ? 
     CircularProgressIndicator()
     : Container(...

Additionally, you can also refactor your initState to something like this此外,您还可以将您的initState重构为类似这样的内容

void getCities() async {
   var snapshot CityServices().getCites();
   setState(() {
        citiesFlag = true;
        cities = snapshot.documents;
        citiesCount = snapshot.documents.length;
      });
}

@override
  void initState() {
    getCities();  
    super.initState();
  }

Long term solution:长期解决方案:
use BLoC pattern and make data loading decoupled from UI.使用BLoC模式并使数据加载与 UI 分离。
see flutter_bloc for how to implement it.有关如何实现它,请参阅flutter_bloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM