提问者:小点点

类型“Null”不是类型“List<Name>”的子类型


这是我根据最近的flutter版本改编的“网络忍者”代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:coffee_for_all/models/coffee.dart';
import 'package:coffee_for_all/services/auth.dart';
import 'package:flutter/material.dart';
import 'package:coffee_for_all/services/database.dart';
import 'package:provider/provider.dart';
import 'coffee_list.dart';

class Home extends StatelessWidget {
  final AuthService _auth = AuthService();

  var initialData;

  @override
  Widget build(BuildContext context) {
    return StreamProvider<List<Coffee>>.value(
      value: DatabaseService().coffees,
      initialData: initialData,
      child: Scaffold(
        backgroundColor: Colors.brown[50],
        appBar: AppBar(
          title: Text('Coffee for all'),
          backgroundColor: Colors.brown[400],
          elevation: 0.0,
          actions: <Widget>[
            TextButton.icon(
              icon: Icon(Icons.person),
              label: Text('logout'),
              style: TextButton.styleFrom(
                primary: Colors.black,
              ),
              onPressed: () async {
                await _auth.signOut();
              },
            )
          ],
        ),
        body: CoffeeList(),
      ),
    );
  }
}

当我尝试运行程序时,这种情况发生: ═════════════════════════════════════════════════════════════ 在937毫秒内重新加载了680个库中的5个。

════════ 被小部件库捕获的异常 ════════════════ 类型'Null'不是类型'List'的子类型相关的导致错误的小部件是Home lib\屏幕\wrapper. dart:18 ══════════════════════════════════════════════════════════════

这就是我定义列表的位置和方式:

class Coffee {
  final String? name;
  final String? sugars;
  final int? strength;

  Coffee({this.name, this.sugars, this.strength});
}


class CoffeeList extends StatefulWidget {
  @override
  _CoffeeListState createState() => _CoffeeListState();
}

class _CoffeeListState extends State<CoffeeList> {
  @override
  Widget build(BuildContext context) {
    final coffees = Provider.of<List<Coffee>>(context);

    return ListView.builder(
      itemCount: coffees.length,
      itemBuilder: (context, index) {
        return CoffeeTile(coffee: coffees[index]);
      },
    );
  }
}


  // coffee list from snapshot
  List<Coffee> _coffeeListFromSnapShop(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
      return Coffee(
        name: doc.get('name') ?? '',
        strength: doc.get('strength') ?? 0,
        sugars: doc.get('sugars') ?? '0',
      );
    }).toList();
  }

  // get coffees stream

  Stream<List<Coffee>> get coffees {
    return coffeeCollection.snapshots().map(_coffeeListFromSnapShop);
  }

有人能帮我解决这个错误吗?谢谢!


共3个答案

匿名用户

试试这个解决方案。ListView. builder()的itemCount属性没有空检查。

 @override
Widget build(BuildContext context) {
final coffees = Provider.of<List<Coffee>>(context);

  return ListView.builder(
    itemCount: coffees!=null?coffees.length:0,
    itemBuilder: (context, index) {
    return CoffeeTile(coffee: coffees[index]);
   },
 );

} }

匿名用户

但这会导致:

════════ Exception caught by widgets library ═══════════════════════════════════
type 'Null' is not a subtype of type 'List<Coffee>'
The relevant error-causing widget was
Home
lib\screens\wrapper.dart:18
════════════════════════════════════════════════════════════════════════════════

作为我的包装文件:

import 'package:coffee_for_all/screens/authenticate/authenticate.dart';
import 'package:coffee_for_all/screens/home/home.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Wrapper extends StatelessWidget {
  const Wrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<Uid?>(context);

    // return either Home or Authenticate widget
    if (user == null) {
      return Authenticate();
    } else {
      return Home();
    }
  }
}

匿名用户

问题是初始数据没有定义,但现在正在使用:

initialData: [],