类型“Null”不是类型“int”的子类型,使用 provider

Type 'Null' is not a subtype of type 'int', using provider

提问人:Pimpi Rimpà 提问时间:9/3/2023 最后编辑:Pimpi Rimpà 更新时间:9/3/2023 访问量:37

问:

当用户点击以保存文章并将其传递到收藏夹页面时,我在尝试从文章中保存 ID 时遇到了这个问题。每次我转到收藏夹页面时,我都会收到此错误消息“类型'Null'不是类型'int'的子类型”。

请问,我该如何解决?

用户点击以保存文章的文章页面enter image description here

文章必须显示的收藏夹页面enter image description here

主要与更改 nofitier 提供程序

class _MyAppState extends State<MyApp> {
  var data;
  var id;
  List<ArticleModel> allArticles = [];

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<FavoriteProvider>(
            create: (context) => FavoriteProvider(allArticles),
            builder: (contex, _) {
              return MaterialApp(
              debugShowCheckedModeBanner: false,
              /// Google Analytics
              navigatorObservers: [locator<AnalyticsService>().getAnalyticsObserve(),],
              theme: assoFacileNewsTheme,
              /// Routes
              initialRoute: "/splashScreen",
              routes: {
              /// Primary pages
              "/splashScreen":              (_) => SplashScreen(),
              "/onboardingScreens":         (_) => OnboardingScreens(),
              /// bottom navigation bar pages
              "/homepage":                  (_) => HomePage(),
              "/formazione":                (_) => FormazionePage(),
              "/favorite_articles":         (_) => FavoritePage(id: id,),
            },
         );
      },
    );
  }
}

ChangeNotifier 页面

class FavoriteProvider extends ChangeNotifier {
  final List<ArticleModel> _allArticles = [];
  final List<int> _favoriteArticleIds = [];
  List<int> get favoriteArticleIds => _favoriteArticleIds;
  int get favoriteCount => _favoriteArticleIds.length;
  FavoriteProvider(List<ArticleModel> allArticles) {allArticles.addAll(allArticles);}
  /// Function to check if an article is favorited
  bool isFavorite(int favoriteArticleIds) {return _favoriteArticleIds.contains(favoriteArticleIds);} // was articleId

  /// Function to add or remove an article from favorites
  void toggleFavorite(int favoriteArticleIds, context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (_favoriteArticleIds.contains(favoriteArticleIds)) {
      _favoriteArticleIds.remove(favoriteArticleIds);
      print("Removed $favoriteArticleIds from _favoriteArticleIds");
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(duration: Duration(seconds: 3),backgroundColor: Colors.white, content: Text("Articolo rimosso", style: TextStyle(color: Colors.black),),),);
    } else {
      _favoriteArticleIds.add(favoriteArticleIds);
      print("Saved $favoriteArticleIds to _favoriteArticleIds");
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(duration: Duration(seconds: 3),backgroundColor: Colors.white, content: Text("Articolo salvato", style: TextStyle(color: Colors.black),),),);
    }
    notifyListeners();
  }

  /// Fetch favourite articles
  Future<List<ArticleModel>> fetchFavoriteArticles() async {
    final favoriteArticles = _allArticles.where((article) => _favoriteArticleIds.contains(article.id)).toList();
    print("Favorite Articles in fetchFavoriteArticles: ${favoriteArticles.length}");
    return favoriteArticles;
  }
}

文章页面

class ArticlePage extends StatefulWidget {
  final int id; final String? urlImage; final String? title; final String? description; final dynamic data;
  const ArticlePage({Key? key, required this.data, required this.id, this.urlImage, this.title, this.description}) : super(key: key);
  @override
  _ArticlePageState createState() => _ArticlePageState(data, id, urlImage, title, description);
}

class _ArticlePageState extends State<ArticlePage> {
  int id;final urlImage;final title;final description;final data;
  late FavoriteProvider favoriteArticles;
  late bool _favoriteArticlesReady;
  late bool isFavorite = false;
  _ArticlePageState(this.data, this.id, this.urlImage, this.title, this.description,);

  /// Function to save and remove articles
  void btnFunction() {
    favoriteArticles.toggleFavorite(widget.id, context);
    setState(() {
      isFavorite = !isFavorite;
    });
  }

  @override
  void initState() {
    super.initState();
    favoriteArticles = Provider.of<FavoriteProvider>(context, listen: false);
    isFavorite = favoriteArticles.isFavorite(widget.id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Consumer<FavoriteProvider>(builder: (context, favoriteArticles, _) {
         return CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              leading: const PreviousBtn(),
              flexibleSpace: FlexibleSpaceBar(
                centerTitle: true,
                background: CachedNetworkImage(
                  imageUrl: data["_embedded"]["wp:featuredmedia"][0]["link"],
                  fit: BoxFit.cover,
                  placeholder: (context, url) => Image.asset("assets/gif/shimmer.gif", fit: BoxFit.cover,),
                  errorWidget: (context, url, error) => Image.asset("assets/images/unloadedImage.png", width: 250, height: 250,
                  ),
                ),
              ),
              actions: [
                Visibility(child: Text(data['id'].toString()), visible: false,),
                /// Favorite icon
                Padding(
                  padding: const EdgeInsets.only(right: 10.0),
                  child: Container(
                      margin: const EdgeInsets.only(top: 12.0, bottom: 10.0,),
                      width: 35,
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(50), color: Colors.white,),
                      child:
                      IconButton(
                        icon: isFavorite
                            ? const Icon(Icons.bookmark_outlined, color: Color(0xFF0D47A1), size: 18,)
                            : const Icon(Icons.bookmark_outline_outlined, color: Color(0xFF0D47A1), size: 18,),
                        onPressed: btnFunction,
                      ),
                  ),
                ),
                /// Share article icon
                Padding(
                  padding: const EdgeInsets.only(right: 15.0),
                  child: IconButton(
                    icon: Image.asset('assets/images/share_icon.png',),
                    onPressed: () {
                      Share.share(data["link"], subject: "Leggi l'articolo di AssoFacile News $title",
                      );
                    },
                  ),
                ),
              ], floating: true, expandedHeight: 320,
            ),
            SliverList(
              delegate: SliverChildListDelegate([
                Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      const SizedBox(height: 20,),
                      /// Article title
                      Text(
                        data["title"]["rendered"].toString().replaceAll("<p>", "").replaceAll("&#8217;", "'").replaceAll("</p>", ""),
                        style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 20, fontFamily: "Raleway",),
                      ),
                      const SizedBox(height: 0),
                      /// Text content
                      HtmlWidget(
                        data['content']['rendered'].toString()
                            .replaceAll("<p>", "")
                            .replaceAll("&#8217;", "'")
                            .replaceAll("<img>", "")
                            .replaceAll("<div>", "<div>").replaceAll("</div>", "</div>")
                            .replaceAll("</p>", ""),
                      ),
                      const SizedBox(height: 20),
                    ],
                  ),
                ),
              ],
              ),
            ),
          ],
         );
        }
      ),
    );
  }
}

文章应该出现的收藏页面

class FavoritePage extends StatefulWidget {
  final int id; final data;
  const FavoritePage({Key? key, this.data, required this.id}) : super(key: key);
  @override
  _FavoritePageState createState() => _FavoritePageState();
}

class _FavoritePageState extends State<FavoritePage> {
  String title  = "Articoli Preferiti";

  @override
  Widget build(BuildContext context) {
    print("Favourite page article id: ${widget.id}");
    final importFavourites = Provider.of<FavoriteProvider>(context, listen: false).fetchFavoriteArticles;
    return Scaffold(
      drawer: NavbarMenu(),
      appBar: CustomAppBar(leadingBtn: const DehazeIconBtn(), title: title,),
      body: FutureBuilder(
        future: importFavourites(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              final favoriteArticlesData = snapshot.data as List<ArticleModel>;
              print("Favorite Articles Length: ${favoriteArticlesData.length}");
              if (favoriteArticlesData.isEmpty) {
                return const EmptyArticle();
              }
              return ListView.builder(
                itemCount: favoriteArticlesData.length,
                itemBuilder: (context, index) {
                  final article = favoriteArticlesData[index];
                  return Card(
                    margin: const EdgeInsets.all(8),
                    elevation: 5,
                    shadowColor: Colors.black26,
                    color: Colors.white,
                    child: InkWell(
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(10),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              height: 190,
                              width: double.infinity,
                              child: Image(
                                image: AdvancedNetworkImage(
                                  article.urlImageSource ?? "", useDiskCache: true, cacheRule: const CacheRule(maxAge: Duration(days: 1)),
                                ), fit: BoxFit.cover,
                              ),
                            ),
                            Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(left: 16, top: 16, bottom: 16),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          article.title?.replaceAll("&#8217;", "'").replaceAll("<p>", "").replaceAll("</p>", "") ?? "",
                                          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, fontFamily: "Raleway",),
                                          overflow: TextOverflow.ellipsis,
                                          maxLines: 2,
                                        ),
                                      ),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                      onTap: () {
                        final id = article.id;
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => ArticlePage(data: article, id: id),
                          ),
                        );
                      },
                    ),
                  );
                },
              );
            } else {
              return const EmptyArticle();
            }
          } else {
            return const CircularProgressIndicator();
          }
        },
      ),
    );
  }
}
null 整数 提供程序 flutter-provider

评论

1赞 Afzal 9/3/2023
如果您可以为此 secnario 创建一个要点,那就太好了,可以轻松查看代码以检查问题所在
0赞 Pimpi Rimpà 9/3/2023
我需要当转到文章页面并且用户点击书签图标将文章保存在收藏夹页面上时,提供商必须将专用于收藏夹页面的文章的文章 ID 传递到收藏夹页面才能显示它。我刚刚添加了更多信息
1赞 John Weidner 9/3/2023
当您将某些内容声明为不应该是 const 时,该错误经常发生。通常,尝试从报告错误的位置删除上一个 const 关键字。
0赞 Pimpi Rimpà 9/4/2023
如您所见,代码中没有任何常量!!!!

答: 暂无答案