Flutter

Some cool things in flutter ecosystem

table of contents


Riverpod

Nice reactive state management for flutter application

Create provider:

final someNotifier = ChangeNotifierProvider((ref) => _SomeState());

class _SomeState extends ChangeNotifier {
  late Box box; // <- you can even use hive here

  _SomeState() {
    box = Hive.box('someBox');
  }

  void someMethod() {
    // some code...

    notifyListeners(); // <- this wil ensure all observers will be notified of value change
  }
}

So.. how to get that data?

  • Stateless widget

class SomePage extends ConsumerWidget {
  SomePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final stateProvider = ref.watch(someNotifier); // <- and now you have access to the provider

    return ... // whatever;
  }
}
  • Stateful widget

class SomeStateFulPage extends ConsumerStatefulWidget {
  const SomeStateFulPage({super.key});

  @override
  _SomeStatefulPageState createState() => _SomeStatefulPageState();
}

class _SomeStatefulPageState extends ConsumerState<SomeStateFulPage> {
	_SomeStatefulPageState();

	@override
	Widget build(BuildContext context) {
		final stateProvider = ref.watch(someNotifier); // <- same thing, you have access to the provider

		return ... // whatever
	}
}

Wrap application in provider scope

In main.dart

  runApp(const ProviderScope(
    child: MyApp(),
  ));

Hive

On-device database that stores data i β€˜boxes’

nice & fast

Create hive class

import 'package:hive/hive.dart';

part 'SomeHiveClass.g.dart'; // <- this file will be generated by command

@HiveType(typeId: 1)
class SomeHiveClass {
  SomeHiveClass({
    required this.name,
    required this.url,
    this.maxZoom = 18,
    this.minZoom = 4,
  });

  @HiveField(0)
  late String name;

  @HiveField(1)
  late String url;

  @HiveField(2, defaultValue: 18)
  late double maxZoom;

  @HiveField(3, defaultValue: 4)
  late double minZoom;
}

Note: You can use default values when you created new version of the class with new fields, but still want to use the same box.

Those new fields can be filled with default values when you want to access old stored items

Generate hive part files

flutter packages pub run build_runner build

Register Adapters in main.dart

Future main() async {
  await Hive.initFlutter();

  Hive.registerAdapter(HivePlotAdapter()); // <- that generated .g.dart file

  await Hive.openBox('currentPlotBox'); // <- name of the box that stores data

  runApp(const ProviderScope( // <- this is from riverpod
    child: MyApp(),
  ));
}

Note to myself: check Try this pattern


Background Fetch

//TODO


Local Notifications

Simple example

import 'dart:developer';

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationService {
  static final NotificationService _singleton =
      new NotificationService._internal();

  var initializationSettingsAndroid = const AndroidInitializationSettings(
    '@mipmap/ic_launcher',
  );

  late InitializationSettings initializationSettings;
  var flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  factory NotificationService() {
    return _singleton;
  }

  NotificationService._internal() {
    initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
    );

    flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveBackgroundNotificationResponse: inspect,
      onDidReceiveNotificationResponse: inspect,
    );
  }

  Future showNotification() async {
    var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
        'Channel id', 'ChannelName',
        importance: Importance.defaultImportance,
        priority: Priority.defaultPriority);

    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
    );

    await flutterLocalNotificationsPlugin.show(
      0,
      'Notification Alert πŸ””',
      'Message - There is a new notification on your account, kindly check it out',
      platformChannelSpecifics,
      payload:
          'Message - There is a new notification on your account, kindly check it out',
    );
  }
}
 Date: November 16, 2023
 Tags:  content flutter

Previous
⏪ Hello World

Next
React ⏩