I'm looking into Flutter and was wondering the best or correct way to do this:
If I have a 'common' object that provides functionality that's useful throughout an application what's the best way to make it easily available?
E.g. I have a service class I want to be available throughout my application on various pages/screens
class MyService{
bool available = true;
bool validString(String s) => true;
bool validNum(num n) => true;
void someFunc() => print("Called");
String formatString(String s) => "Formatted String";
String defaultString() => "Default String";
// ....
}
The best example I came across for doing this starts by initialising a single instance of this class on application start in main.dart
(first line)
MyService service = new MyService();
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
Then any route/screen/widget that needs the service imports main and just calls it via the previously initialised object
import 'main.dart';
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
service.defaultString(),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => service.available ? service.someFunc() : print("Service Unavailable"),
tooltip: 'Validate',
child: Icon(Icons.question_answer),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Is there a better/cleaner way to do this?