Android 如何从控制器层获取devicePixelRatio颤振
我是颤振的初学者,现在我正在学习MVC模式,我正在使用GetX进行状态管理 我需要为devicePixelRatio参数传递一个double类型的值,如下图所示 但是,我无法在控制器内恢复此值,因为我没有“上下文” 是否可以在控制器中获取此值?还是通过视图层传递此值Android 如何从控制器层获取devicePixelRatio颤振,android,flutter,dart,getx,Android,Flutter,Dart,Getx,我是颤振的初学者,现在我正在学习MVC模式,我正在使用GetX进行状态管理 我需要为devicePixelRatio参数传递一个double类型的值,如下图所示 但是,我无法在控制器内恢复此值,因为我没有“上下文” 是否可以在控制器中获取此值?还是通过视图层传递此值 我寻找了解决方案,但没有找到答案,如果有人能提供帮助,请提前感谢。您可以复制粘贴运行下面的完整代码 我使用官方示例来模拟这个案例 您可以使用double pixelRatio=Get.context.devicePixelRat
我寻找了解决方案,但没有找到答案,如果有人能提供帮助,请提前感谢。您可以复制粘贴运行下面的完整代码
我使用官方示例来模拟这个案例
您可以使用
double pixelRatio=Get.context.devicePixelRatio代码>
代码片段
class Controller extends GetxController {
double pixelRatio = Get.context.devicePixelRatio;
int count = 0;
void increment() {
print("pixelRatio $pixelRatio");
count++;
// use update method to update all count variables
update();
}
}
单击浮动操作按钮时输出
I/flutter (19594): pixelRatio 3.5
完整代码
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(GetMaterialApp(
// It is not mandatory to use named routes, but dynamic urls are interesting.
initialRoute: '/home',
defaultTransition: Transition.native,
translations: MyTranslations(),
locale: Locale('pt', 'BR'),
getPages: [
//Simple GetPage
GetPage(name: '/home', page: () => First()),
// GetPage with custom transitions and bindings
GetPage(
name: '/second',
page: () => Second(),
customTransition: SizeTransitions(),
binding: SampleBind(),
),
// GetPage with default transitions
GetPage(
name: '/third',
transition: Transition.cupertino,
page: () => Third(),
),
],
));
}
class MyTranslations extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'en': {
'title': 'Hello World %s',
},
'en_US': {
'title': 'Hello World from US',
},
'pt': {
'title': 'Olá de Portugal',
},
'pt_BR': {
'title': 'Olá do Brasil',
},
};
}
class Controller extends GetxController {
double pixelRatio = Get.context.devicePixelRatio;
int count = 0;
void increment() {
print("pixelRatio $pixelRatio");
count++;
// use update method to update all count variables
update();
}
}
class First extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.add),
onPressed: () {
Get.snackbar("Hi", "I'm modern snackbar");
},
),
title: Text("title".trArgs(['John'])),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GetBuilder<Controller>(
init: Controller(),
// You can initialize your controller here the first time. Don't use init in your other GetBuilders of same controller
builder: (_) => Text(
'clicks: ${_.count}',
)),
RaisedButton(
child: Text('Next Route'),
onPressed: () {
Get.toNamed('/second');
},
),
RaisedButton(
child: Text('Change locale to English'),
onPressed: () {
Get.updateLocale(Locale('en', 'UK'));
},
),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Get.find<Controller>().increment();
}),
);
}
}
class Second extends GetView<ControllerX> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('second Route'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GetX<ControllerX>(
// Using bindings you don't need of init: method
// Using Getx you can take controller instance of "builder: (_)"
builder: (_) {
print("count1 rebuild");
return Text('${_.count1}');
},
),
GetX<ControllerX>(
builder: (_) {
print("count2 rebuild");
return Text('${controller.count2}');
},
),
GetX<ControllerX>(builder: (_) {
print("sum rebuild");
return Text('${_.sum}');
}),
GetX<ControllerX>(
builder: (_) => Text('Name: ${controller.user.value.name}'),
),
GetX<ControllerX>(
builder: (_) => Text('Age: ${_.user.value.age}'),
),
RaisedButton(
child: Text("Go to last page"),
onPressed: () {
Get.toNamed('/third', arguments: 'arguments of second');
},
),
RaisedButton(
child: Text("Back page and open snackbar"),
onPressed: () {
Get.back();
Get.snackbar(
'User 123',
'Successfully created',
);
},
),
RaisedButton(
child: Text("Increment"),
onPressed: () {
Get.find<ControllerX>().increment();
},
),
RaisedButton(
child: Text("Increment"),
onPressed: () {
Get.find<ControllerX>().increment2();
},
),
RaisedButton(
child: Text("Update name"),
onPressed: () {
Get.find<ControllerX>().updateUser();
},
),
RaisedButton(
child: Text("Dispose worker"),
onPressed: () {
Get.find<ControllerX>().disposeWorker();
},
),
],
),
),
);
}
}
class Third extends GetView<ControllerX> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed: () {
controller.incrementList();
}),
appBar: AppBar(
title: Text("Third ${Get.arguments}"),
),
body: Center(
child: Obx(() => ListView.builder(
itemCount: controller.list.length,
itemBuilder: (context, index) {
return Text("${controller.list[index]}");
}))),
);
}
}
class SampleBind extends Bindings {
@override
void dependencies() {
Get.lazyPut<ControllerX>(() => ControllerX());
}
}
class User {
User({this.name = 'Name', this.age = 0});
String name;
int age;
}
class ControllerX extends GetxController {
final count1 = 0.obs;
final count2 = 0.obs;
final list = [56].obs;
final user = User().obs;
updateUser() {
user.update((value) {
value.name = 'Jose';
value.age = 30;
});
}
/// Once the controller has entered memory, onInit will be called.
/// It is preferable to use onInit instead of class constructors or initState method.
/// Use onInit to trigger initial events like API searches, listeners registration
/// or Workers registration.
/// Workers are event handlers, they do not modify the final result,
/// but it allows you to listen to an event and trigger customized actions.
/// Here is an outline of how you can use them:
/// made this if you need cancel you worker
Worker _ever;
@override
onInit() {
/// Called every time the variable $_ is changed
_ever = ever(count1, (_) => print("$_ has been changed (ever)"));
everAll([count1, count2], (_) => print("$_ has been changed (everAll)"));
/// Called first time the variable $_ is changed
once(count1, (_) => print("$_ was changed once (once)"));
/// Anti DDos - Called every time the user stops typing for 1 second, for example.
debounce(count1, (_) => print("debouce$_ (debounce)"),
time: Duration(seconds: 1));
/// Ignore all changes within 1 second.
interval(count1, (_) => print("interval $_ (interval)"),
time: Duration(seconds: 1));
}
int get sum => count1.value + count2.value;
increment() => count1.value++;
increment2() => count2.value++;
disposeWorker() {
_ever.dispose();
// or _ever();
}
incrementList() => list.add(75);
}
class SizeTransitions extends CustomTransition {
@override
Widget buildTransition(
BuildContext context,
Curve curve,
Alignment alignment,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
return Align(
alignment: Alignment.center,
child: SizeTransition(
sizeFactor: CurvedAnimation(
parent: animation,
curve: curve,
),
child: child,
),
);
}
}
导入“包装:颤振/材料.省道”;
导入“package:get/get.dart”;
void main(){
runApp(GetMaterialApp(
//使用命名路由不是强制性的,但动态URL很有趣。
initialRoute:“/home”,
defaultTransition:Transition.native,
翻译:MyTranslations(),
语言环境:语言环境('pt','BR'),
获取网页:[
//简单获取页面
GetPage(名称:'/home',页面:()=>First()),
//具有自定义转换和绑定的GetPage
GetPage(
名称:'/second',
页面:()=>Second(),
customTransition:SizeTransitions(),
绑定:SampleBind(),
),
//具有默认转换的GetPage
GetPage(
名称:'/third',
过渡:transition.cupertino,
页面:()=>Third(),
),
],
));
}
类MyTranslations扩展了翻译{
@凌驾
映射获取密钥=>{
"嗯":{
'title':'Hello World%s',
},
“恩,我们”{
‘标题’:‘你好,我们的世界’,
},
“pt”:{
“标题”:“葡萄牙奥兰多”,
},
“pt_BR”:{
“标题”:“Oládo Brasil”,
},
};
}
类控制器扩展了GetxController{
double pixelRatio=Get.context.devicePixelRatio;
整数计数=0;
无效增量(){
打印(“pixelRatio$pixelRatio”);
计数++;
//使用update方法更新所有计数变量
更新();
}
}
类优先扩展无状态小部件{
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
领先:IconButton(
图标:图标(Icons.add),
已按下:(){
Get.snackbar(“嗨”,“我是现代snackbar”);
},
),
标题:文本(“title”.trArgs(['John']),
),
正文:中(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
GetBuilder(
init:Controller(),
//您可以第一次在这里初始化控制器。不要在同一控制器的其他GetBuilder中使用init
生成器:()=>文本(
'单击:${.count}',
)),
升起的按钮(
子项:文本(“下一条路线”),
已按下:(){
Get.toNamed('/second');
},
),
升起的按钮(
子项:Text('Change locale to English'),
已按下:(){
Get.updateLocale(Locale('en','UK');
},
),
],
),
),
浮动操作按钮:浮动操作按钮(
子:图标(Icons.add),
已按下:(){
Get.find().increment();
}),
);
}
}
第二类扩展了GetView{
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“第二条路线”),
),
正文:中(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
GetX(
//使用不需要init:method的绑定
//使用Getx,您可以获取“builder:(\ux)”的控制器实例
建筑商:(){
打印(“count1重建”);
返回文本(“${count1}”);
},
),
GetX(
建筑商:(){
打印(“count2重建”);
返回文本(“${controller.count2}”);
},
),
GetX(建筑商:(){
打印(“金额重建”);
返回文本(“${sum}”);
}),
GetX(
生成器:()=>Text('Name:${controller.user.value.Name}),
),
GetX(
生成器:()=>Text('Age:${{uu.user.value.Age}),
),
升起的按钮(
子项:文本(“转到最后一页”),
已按下:(){
Get.toNamed('/third',arguments:'arguments of second');
},
),
升起的按钮(
子项:文本(“返回页和打开snackbar”),
已按下:(){
返回();
快去吃零食吧(
“用户123”,
“已成功创建”,
);
},
),
升起的按钮(
子项:文本(“增量”),
已按下:(){
Get.find().increment();
},
),
升起的按钮(
子项:文本(“增量”),
已按下:(){
Get.find().increment2();
},
),
升起的按钮(
子项:文本(“更新名称”),
已按下:(){
Get.find().updateUser();
},
),
升起的按钮(
子项:文本(“Dispose worker”),
已按下:(){
Get.find().disposeWorker();
},
),
],
),
),
);
}
}
第三类扩展了GetView{
@凌驾
威德