iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😈

Implementing Firebase Remote Config in a Flutter App

に公開1件

Introduction

I would like to document the steps for integrating Firebase's Remote Config into a Flutter app as a personal memo.
I would appreciate any feedback if there are any points that could be improved. 🙇


Benefits of Introducing Remote Config

By leveraging Remote Config, you can change values without updating the app. This allows for immediate reflection when you want to change names or images displayed on the screen in top content areas of the app, for example.


Introducing Necessary Packages

In pubspec.yaml under dependencies, add firebase_core and firebase_remote_config.
Also, for state management, add hooks_riverpod.

As many of you may know, it's convenient to install the Pubspec Assist extension when adding packages in Flutter.
https://marketplace.visualstudio.com/items?itemName=jeroen-meijer.pubspec-assist

After installation, packages can be added using the following steps:

  1. Call the command palette with shift + command + p
  2. Select Pubspec Assist:add dependencies
  3. Enter the required package names (the auto-completion feature is helpful even if the spelling is vague).

Writing Code

Preparation

First, enable Remote Config on Firebase.
The steps are as follows:

  1. In your Firebase project, navigate to Engagement > Remote Config from the left sidebar.
  2. Click the "Create configuration" button to create a parameter.

For now, I'll create a simple parameter that summarizes Remote Config.

Next, after running flutter create, I will organize the file structure based on the MVVM design pattern.
https://wasabeef.medium.com/flutter-を-mvvm-で実装する-861c5dbcc565

Here is the folder structure beforehand:

Now, let's write some code!

First, to enable Riverpod, simply wrap the widget in runApp (in this case, MyApp) with a ProviderScope widget.

lib/main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import 'src/ui/my_app/my_app_page.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  runApp(ProviderScope(child: _MaterialApp()));
}

class _MaterialApp extends StatelessWidget {
  @override
  MaterialApp build(BuildContext context) => const MaterialApp(
        title: 'RemoteConfigPractice',
        home: MyApp(),
      );
}

I will include the code for MyApp later when creating the view.


Creating the Model (resources & repository)

Referring to FlutterFire, I will write the necessary code to introduce RemoteConfig.

lib/src/resources/firebase/remote_config_service.dart
​import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

final remoteConfigServiceProvider = Provider((_) => RemoteConfigService());

class RemoteConfigService {
  RemoteConfig? _remoteConfig;

  Future<void> getRemoteConfig() async {
    _remoteConfig = RemoteConfig.instance;
    await _remoteConfig?.setConfigSettings(RemoteConfigSettings(
      fetchTimeout: const Duration(seconds: 10),
      minimumFetchInterval: const Duration(hours: 1),
    ));//The above two lines are configured as per the official documentation.
    await _remoteConfig?.fetchAndActivate();
  }

  Future<RemoteConfigValue> getValue(String key) async =>
      _remoteConfig!.getValue(key);
}

Here is a brief explanation of each method:

.getRemoteConfig
A method that needs to be called when the app launches.

・getValue
A method that fetches RemoteConfig data for each parameter. The argument to this method is the parameter name that was set in Firebase (RemoteConfig).


Next, let's move to the repository.
The purpose of the repository is to separate business logic from data operations, so that the ViewModel does not need to be aware of where data is retrieved or updated.

lib/src/repository/remote_config/remote_content_repository.dart
import 'dart:convert';
import 'dart:io';

import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../resources/entities/remote_content.dart';
import '../../resources/firebase/remote_config_service.dart';

final remoteContentRepositoryProvider =
    Provider<RemoteContentRepository>((ref) {
  final remoteConfigService = ref.read(remoteConfigServiceProvider);
  return RemoteContentRepository(remoteConfigService: remoteConfigService);
});

class RemoteContentRepository {
  RemoteContentRepository({
    required this.remoteConfigService,
  });

  final RemoteConfigService remoteConfigService;

  //Method to pass to ViewModel
  Future<List<RemoteContent>> fetchRemoteContents() async {
    final data = await remoteConfigService.getValue('RemoteConfig');
    // ignore: unnecessary_null_comparison
    if (data == null) {
      throw const HttpException(
          'Failed to get Remote Config or under loading.');
    }
    final decoded = json.decode((data).asString()).cast<Map<String, dynamic>>()
        as List<Map<String, dynamic>>;
    final remoteContent = await Future.wait(decoded.map(
      (content) async => RemoteContent.fromJson(content),
    ));
    // ignore: unnecessary_null_comparison
    remoteContent.removeWhere((content) => content == null);
    return remoteContent;
  }
}

The RemoteContent mentioned here is a model class defined to avoid typos when calling the content described in the JSON editor in the view.
It is defined in a separate file.
title and content are what I edited earlier in Firebase (RemoteConfig).

lib/src/repository/remote_config/remote_content_repository.dart
class RemoteContent {
  RemoteContent({
    required this.title,
    required this.content,
  });

  factory RemoteContent.fromJson(Map<String, dynamic> data) => RemoteContent(
        title: data['title'],
        content: data['content'],
      );

  final String title;
  final String content;
}

That concludes the Model description. Next, we move on to the ViewModel.


Creating the ViewModel

If state management is required, the ViewModel is typically provided on a one-to-one basis for each view. So, in this case, we will prepare a ViewModel file in the my_app folder.

The ViewModel has two main roles:

  • Appropriately transform the state (data) entered from the View and hold it as a Model.
  • Pass the Model's state (data) to the View to prompt screen updates.

This time, we want to do precisely the second point: pass the Model (RemoteConfig) data (parameters) to the view to prompt screen updates.
Here is the code:

lib/src/ui/my_app/view_model.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../repository/remote_content_repository.dart';
import '../../resources/entities/remote_content.dart';
import '../../resources/firebase/remote_config_service.dart';

final myAppPageViewModelProvider = ChangeNotifierProvider.autoDispose((ref) {
  final remoteConfigService = ref.read(remoteConfigServiceProvider);
  final remoteContentRepository = ref.read(remoteContentRepositoryProvider);
  return _MyAppPageViewModel(
    remoteConfigService: remoteConfigService,
    remoteContentRepository: remoteContentRepository,
  );
});

class _MyAppPageViewModel extends ChangeNotifier {
  _MyAppPageViewModel({
    required this.remoteConfigService,
    required this.remoteContentRepository,
  }) {
    _initialize();
  }
  final RemoteConfigService remoteConfigService;
  final RemoteContentRepository remoteContentRepository;

  AsyncValue<List<RemoteContent>> _remoteContents = const AsyncValue.loading();
  AsyncValue<List<RemoteContent>> get remoteContents => _remoteContents;

  bool _isLoading = true;
  bool get isLoading => _isLoading;

  Future<void> _initialize() async {
    try {
      await remoteConfigService.getRemoteConfig();
      _isLoading = false;

      final remoteContents =
          await remoteContentRepository.fetchRemoteContents();
      _remoteContents = AsyncValue.data(remoteContents);
      notifyListeners();
    } on Exception catch (e) {
      print(e);
      _remoteContents = AsyncValue.error(e);
    }
  }
}

Describing the View

Finally, the view (my_app_page).
The following article is helpful for explaining AsyncValue (in this case, remoteContents):
https://qiita.com/toda-axiaworks/items/7950cd28c39de18f4ecc

lib/src/ui/my_app/my_app_page.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../common/error_page.dart';
import '../../common/loading_page.dart';
import '../../common_style.dart';
import 'view_model.dart';

class MyApp extends HookConsumerWidget {
  const MyApp();
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.watch(myAppPageViewModelProvider);
    final isLoading = viewModel.isLoading;

    if (isLoading) {
      return const LoadingPage();
    }

    return Scaffold(
      body: viewModel.remoteContents.when(
        loading: () => const LoadingPage(),
        error: (_, __) => const ErrorPage(),
        data: (contents) => SafeArea(
          child: ListView.builder(
            itemCount: contents.length,
            itemBuilder: (context, index) {
              final content = contents[index];
              return Container(
                margin: const EdgeInsets.symmetric(vertical: 15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: const EdgeInsets.fromLTRB(15, 0, 15, 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          content.title.isEmpty
                              ? const SizedBox()
                              : Text(
                                  content.title,
                                  style: CommonTextStyles.remoteContentTitle,
                                ),
                          const SizedBox(height: 10),
                          content.content.isEmpty
                              ? const SizedBox()
                              : Text(
                                  content.content,
                                  style: CommonTextStyles.remoteContent,
                                ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

With the code above, the data from RemoteConfig is now reflected on the screen!

That's all. Thank you for reading!

Discussion

nekotaronekotaro

Riverpod公式でChangeNotifierProviderは非推奨なので使用しないほうが良さそうです。
この場面ではFeatureProviderを使うのがよさそうです。