【问题标题】:Flutter provider length was called on null在 null 上调用了 Flutter 提供程序长度
【发布时间】:2020-11-18 03:42:37
【问题描述】:

我有一个使用颤振提供程序的列表。但是 firestore 数据有效。问题是那个提供程序。错误是在 null 上调用了 getter 长度。我在stackoverflow中搜索了这个问题,我尝试了每一个答案,但他们没有解决我的问题。下面是包含的代码:

游戏服务类

class GamesServices {
  String collection = 'games';
  Firestore _firestore = Firestore.instance;

  Future<List<GamesModel>> getGames() async {
    _firestore.collection(collection).getDocuments().then((result) {
      List<GamesModel> gameList = <GamesModel>[];
      for (DocumentSnapshot game in result.documents) {
        gameList.add(GamesModel.fromSnapshot(game));
      }
      return gameList;
    });
  }

提供者类

class BoshphelmProvider with ChangeNotifier {
  GamesServices _gamesServices = GamesServices();
  List<GamesModel> _games = <GamesModel>[];

  List<GamesModel> get games => _games;

  BoshphelmProvider.initialize() {
    loadGames();
  }

  loadGames() async {
    _games = await _gamesServices.getGames();
    notifyListeners();
  }
}

主类


void main() {
  setupLocator();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: BoshphelmProvider.initialize(),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Boshphelm',
        theme: ThemeData(
          primaryColor: Constant.primaryColor,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: HomePage(),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter flutter-layout flutter-provider


    【解决方案1】:

    您错过了尝试获取 length 的代码部分,它会引发该错误

    如果没有它,我猜你会在它完成初始化之前尝试访问 games 列表,因为你不需要等待它

    试试这个

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      BoshphelmProvider _provider = BoshphelmProvider();
      await _provider.initialize()
      setupLocator();
      runApp(MyApp()); 
    }
    
    class MyApp extends StatefulWidget {
    
    
    @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider.value(
          value: _provider,
          child: MaterialApp(
            debugShowCheckedModeBanner: false,
            title: 'Boshphelm',
            theme: ThemeData(
              primaryColor: Constant.primaryColor,
              visualDensity: VisualDensity.adaptivePlatformDensity,
            ),
            home: HomePage(),
          ),
        );
      }
    }
    

    【讨论】:

    • 感谢您的回答。我试过你的答案,但它不起作用。
    • @ÇağlaDoğançay 你能分享抛出“长度被调用为空”异常的对象吗?
    猜你喜欢
    • 2019-11-17
    • 2020-03-20
    • 2023-04-03
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2020-10-01
    相关资源
    最近更新 更多