Skip to content

Instantly share code, notes, and snippets.

@eduardoflorence
Created January 13, 2021 19:29
Show Gist options
  • Save eduardoflorence/c43e0b5ac327acb5666629597576b561 to your computer and use it in GitHub Desktop.
Save eduardoflorence/c43e0b5ac327acb5666629597576b561 to your computer and use it in GitHub Desktop.
GetX - Sample GetWidget
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(GetMaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/home',
defaultTransition: Transition.fade,
getPages: [
GetPage(
name: '/home',
page: () => HomePage(),
),
GetPage(
name: '/shop',
page: () => ShopPage(),
binding: ShopBinding(),
),
],
));
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('HOME')),
body: Center(
child: RaisedButton(
color: Colors.blue,
onPressed: () => Get.toNamed('/shop'),
child: Text(
'Go to Shop',
style: TextStyle(color: Colors.white, fontSize: 16),
),
),
),
);
}
}
class ShopBinding extends Bindings {
@override
void dependencies() {
Get.put(ShopController());
Get.create(() => ShopItemController());
}
}
class ShopController extends GetxController {
final total = 0.obs;
final list = ['item 1', 'item 2', 'item 3'].obs;
void increment() => total.value += 1;
void addLista() => list.add('item ${(list.length + 1).toString()}');
}
class ShopPage extends GetView<ShopController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('SHOP')),
body: Column(
children: [
Obx(() => Text('Total: ${controller.total}')),
Flexible(
child: Obx(
() => ListView.builder(
itemCount: controller.list.length,
itemBuilder: (context, item) {
String produto = controller.list[item];
return ShopItem(produto: produto);
},
),
),
),
],
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
controller.addLista();
},
),
);
}
}
class ShopItemController extends GetxController {
final quantity = 0.obs;
ShopController shop = Get.find<ShopController>();
void increment() {
quantity.value += 1;
shop.total.value += 1;
}
}
class ShopItem extends GetWidget<ShopItemController> {
ShopItem({Key key, this.produto}) : super(key: key);
final String produto;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text(produto),
SizedBox(width: 10),
Obx(() => Text('Qty: ${controller.quantity.toString()}')),
SizedBox(width: 10),
RaisedButton.icon(
onPressed: () => controller.increment(),
icon: Icon(Icons.add),
label: Text('add'),
)
],
);
}
}
@ProZhar
Copy link

ProZhar commented Oct 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment