Home > front end >  A provider is not being created or called, but other is
A provider is not being created or called, but other is

Time:01-19

I'm trying to have multiple ChangeNotifierProvider in my app, and the first one I created works great, but when I literally copied over the code into another provider the second one will not work. I've tried nesting them, only creating the second one and using a MultiProvider.

Here is my main:

runApp(MultiProvider(providers: [
  ChangeNotifierProvider(create: (context) => ArticleProvider()),
  ChangeNotifierProvider(create: (context) => CategoryProvider()),
], child: const InsidanApp()));

My first provider:

import 'package:flutter/material.dart';
...

class ArticleProvider extends ChangeNotifier {
  /* Data handling and stuffs */

  /// Fetch articles from the API.
  Future<void> fetchArticles() async {
    print('fetchArticles()');
    // Calculate page number.
    const perPage = 50;
    final page = (_articles.length / perPage).ceil()   1;

    // Fetch articles from API.
    final newArticles =
        await ArticleService.fetchArticles(page: page, count: perPage);
    addAll(newArticles);
    print('Fetched ${newArticles.length} articles.');
  }

  /// Constructor.
  ArticleProvider() {
    print('ArticleProvider()');
    fetchArticles();
  }
}

My second provider:

import 'package:flutter/material.dart';
...

class CategoryProvider extends ChangeNotifier {
  /* Data handling stuff. */

  /// Fetch categories from the API.
  Future<void> fetchCategories() async {
    final newCategories = await CategoryService.fetchCategories();
    addAll(newCategories);
  }

  /// Constructor.
  CategoryProvider() {
    fetchCategories();
  }
}

Do you have any ideas for what the issue could be?

CodePudding user response:

MultiProvider(providers: [
  ChangeNotifierProvider.value(value: ArticleProvider()),
  ChangeNotifierProvider.value(value: CategoryProvider()),
]

Try it this way to see if it works.
  • Related