Next article, this article mainly introduces, route management, internationalization management, responsive management method, data persistence management. Or take a look at the gods are how to write, learn from it. Getx, another handy library, contains almost all of the stuff you’re going to encapsulate today, so use it. Ps: Some people may have the idea that they should write, always use the third party library, encounter problems not to deal with, a little truth, change the idea if they did not reach the level can also use the third party library first, take a good look at the source code of daishen, to improve themselves. Anyway, let’s see it face to face.
The introduction of GetX
Add to pubspec.yaml file
dependencies:
get: ^3.24. 0
Copy the code
Import in the files you want to use
import 'package:get/get.dart';
Copy the code
Replace the MaterialApp with GetMaterialApp in main.dart
return GetMaterialApp(
enableLog: false,
debugShowCheckedModeBanner: false,
defaultTransition: Transition.rightToLeftWithFade,
theme: ThemeData(
primarySwatch: Colors.orange,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: TabBarPage());
Copy the code
Routing management
Why I like this: Jump to the page without getting the context, the code is concise, and alias route jump effects are supported:
Jump without parameters
Get.to(OtherPage())
Copy the code
Jump with parameters
Get.to(OtherPage(id:' '))
Copy the code
No return jump
For example, a jump after a successful login cannot return to the login page
Get.off(OtherPage(id:' '))
Copy the code
Jump to the Tabbar page
For example, from the product details page, jump directly to the shopping cart page, which is usually on Tabbar.
Get.off(TabbarPage(currentIndex: 1));
Copy the code
The alias jump
You can look at the GetX documentation for this, but I won’t cover it here. Because I’m not going to do this jump in the project. Ps: Purely personal reasons
SnackBars, Dialogs, BottomSheets are used
GetX, we can also skip without getting the context using SnackBars, Dialogs, BottomSheets
SnackBars
Effect:
Get.snackbar(
"Hey i'm a Get SnackBar!"."It's unbelievable! I'm using SnackBar without context, without boilerplate, without Scaffold, it is something truly amazing!",
icon: Icon(Icons.alarm),
shouldIconPulse: true,
barBlur: 20,
isDismissible: true,
duration: Duration(seconds: 3),
backgroundColor: Colors.red);
Copy the code
Specific properties, you can click to see the source code configuration
Dialogs
Effect:
Get.defaultDialog(
onConfirm: () => print("Ok"),
buttonColor: Colors.white,
middleText: "Dialog made in 3 lines of code");
Copy the code
You can also play custom components
Get.dialog(YourDialogWidget());
Copy the code
BottomSheets
Effect:
Get.bottomSheet(Container(
decoration: BoxDecoration(color: Colors.red),
child: Wrap(
children: <Widget>[
ListTile(
leading: Icon(Icons.music_note),
title: Text('Music'),
onTap: () {}),
ListTile(
leading: Icon(Icons.videocam),
title: Text('Video'), onTap: () {},),],),);Copy the code
This is a simple way to use it. We can create a new folder called Utils and wrap it into a utility class to call this method.
International management
There are two modes involved,
- Set internationalization according to the system language
- Set the internationalization display within the application
Dart file with the simple meaning of hello in Both Chinese and English
import 'package:get/get.dart';
class Languages extends Translations{@override
Map<String.Map<String.String>> get keys => {
'zh_CN': {
'hello': Hello world,},'en_US': {
'hello': 'Hallo Welt',}}; }Copy the code
Add code to main.dart:
returnGetMaterialApp(Translations: Languages(), translations: Languages(),'zh'.'CN'), // will translate fallbackLocale: Locale('en'.'US'), // add a callback language option in case the language translation specified above does not exist);Copy the code
Display only need to add the following ok. Very simple
Text('hello'.tr)
Copy the code
Follow system language
Ui.window. locale Obtains the current system language and sets the local language
GetMaterialApp(Translations: Languages(), // Your translation locale: ui.window.locale, // will translate fallbackLocale: locale ('en'.'US'), // add a callback language option in case the language translation specified above does not exist......)Copy the code
Set the internationalization display within the application
The updated text is displayed in Chinese as follows:
var locale = Locale('zh'.'CN');
Get.updateLocale(locale);
Copy the code
Write two more sentences using RadioListTile to achieve the effect
RadioListTile(
value: 'chinese',
groupValue: _selected,
title: Text('Chinese'),
subtitle: Text('Chinese'),
selected: _selected == 'chinese',
onChanged: (type) {
var locale = Locale('zh'.'CN');
Get.updateLocale(locale);
setState(() {
_selected = type;
});
}),
RadioListTile(
value: 'english',
groupValue: _selected,
title: Text('English'),
subtitle: Text('English'),
selected: _selected == 'english',
onChanged: (type) {
var locale = Locale('en'.'US');
Get.updateLocale(locale);
setState(() {
_selected = type; }); },),Copy the code
This is my test using the code. Let’s see what happens
Responsive management approach
The GetX example is an example of a counter that is already easy to understand in order to eliminate the need to introduce too many state-management libraries such as provide. The usage is similar. More concise. Or record, convenient later check with
class Controller extends GetxController{
var count = 0.obs;
increment() = >count+ +; }Copy the code
lass Home extends StatelessWidget {
@overrideWidget Build (context) {// instantiate your class using get.put () to make it available to all current child routes. final Controller c = Get.put(Controller());returnScaffold(// uses Obx(()=> Updates Text() whenever the count changes. appBar: AppBar(title: Obx(() => Text("Clicks: ${c.count}"))), // Replace Navigator. Push with a simple get.to ()8Line, no context! body: Center(child: RaisedButton( child: Text("Go to Other"), onPressed: () => Get.to(Other()))), floatingActionButton: FloatingActionButton(child: Icon(Icons.add), onPressed: c.increment)); }}class Other extends StatelessWidget{// You can makeGetFind one that is being used by another pageControllerAnd return it to you.final Controller c = Get.find(a); @override
Widget build(context){// Access the updated count variablereturn Scaffold(body: Center(child: Text("${c.count}"))); }}Copy the code
This is not used in the application yet, but state management can be used in the application easily, such as changing user information and logging in. All available in the shopping cart logic
Data persistence management
This place introduces a second third-party library
flustars: ^0.33.
# https://github.com/Sky24n/sp_util
# sp_util is split into separate libraries that can be referenced directly
sp_util: ^1.01.
Copy the code
It’s easy to use and it feels good. Dart file to initialize for future use
import 'package:flustars/flustars.dart'; class Global { static Future initSqutil() async => await SpUtil.getInstance(); } call global.initsqutil () in main;Copy the code
The following methods are used to store data and get it: string, Boolean, object, array
SpUtil. PutString ('login', 'login',); GetString ('login',defValue: '');Copy the code
An extra point is to store an array of object types in two forms, getObjList and getObjectList methods
List<Map> dataList = SpUtil. GetObjList ('cityMap', (v) => v); List<Map> dataList = sputil.getobjectList ('cityMap');Copy the code
This place can be used in conjunction with international language switching. Like every time you change the language. And then every time I open my app, I get the initialization.
one more things…
- Network request
- Page different states display encapsulation