Created
November 15, 2022 03:38
-
-
Save MelbourneDeveloper/22af958c1e7045913702402bdfe93628 to your computer and use it in GitHub Desktop.
Function Mocking Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:ioc_container/ioc_container.dart'; | |
import 'package:url_launcher/url_launcher.dart'; | |
final flutterDevUri = Uri.parse('https://www.flutter.dev'); | |
///A type alias for the launchUrl's function signature | |
typedef LaunchUrl = Future<bool> Function( | |
Uri url, { | |
//We accept nulls here because we cannot use default | |
//values in type aliases | |
LaunchMode? mode, | |
WebViewConfiguration? webViewConfiguration, | |
String? webOnlyWindowName, | |
}); | |
///Composition root. This is where we wire up dependencies | |
IocContainerBuilder compose() => IocContainerBuilder( | |
allowOverrides: true, | |
) | |
..addSingletonService<LaunchUrl>( | |
//This is how we map the LaunchUrl type on to the actual function | |
//Yes, this is a bit clunky, but using it in the app is very simple | |
(url, {mode, webOnlyWindowName, webViewConfiguration}) async => | |
launchUrl( | |
url, | |
mode: mode ?? LaunchMode.platformDefault, | |
webViewConfiguration: | |
webViewConfiguration ?? const WebViewConfiguration(), | |
webOnlyWindowName: webOnlyWindowName, | |
), | |
) | |
..add((container) => MyApp(launchUrl: container<LaunchUrl>())); | |
void main() => runApp(compose().toContainer()<MyApp>()); | |
class MyApp extends StatelessWidget { | |
const MyApp({ | |
required this.launchUrl, | |
super.key, | |
}); | |
final LaunchUrl launchUrl; | |
@override | |
Widget build(BuildContext context) => MaterialApp( | |
debugShowCheckedModeBanner: false, | |
title: 'Function Mocking Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: Scaffold( | |
body: Align( | |
child: MaterialButton( | |
onPressed: () async { | |
await launchUrl(flutterDevUri); | |
}, | |
color: Colors.blue, | |
textColor: Colors.white, | |
padding: const EdgeInsets.all(40), | |
shape: const CircleBorder(), | |
child: const Icon( | |
Icons.favorite, | |
size: 50, | |
), | |
), | |
), | |
), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment