ListView Shopping getx No null safety
Here, We are learning below the points:
- What is GetX?
- How to implement GetX?
- GetX using Insert, Update, Search (Filter), Favourite, No. of items shopping, Total amount get.
- Custom widget TextField in flutter.
- Null safety using getX using Insert, Update, Search (Filter), Favourite, No. of items shopping, Total amount get with Custom widget TextField
What is GetX in flutter?
- GetX is State management pattern.
- GetX is not only state management patterns but different types of provides utilities likes Dependency Injection and Route (Navigation), Validation.
How to implement GetX in flutter
pubspec.yaml add package: get:
package name: import ‘package:get/get.dart’;
Remove MaterialApp add new GetMaterialApp (Easy to implement only front add Get)
Which condition use to GetMaterialApp:
- GetView
- GetX using navigation. For example: Get.back()
- Need to controller binding
In this post GetX main points:
- GetMaterialApp: GetMaterialApp provide the extra utilities
- GetxController: Put your logic part. For example favourite, no. items shopping, API using fetch data.
- .obs
- obx(() => Widget()), GetX and GetBuilder need to update() method call: Refresh data
- Binding: SmartManager configuration control.
- Get.find(), Get.put(): Access controller data. For example: variable, method
- GetXController lifecycle
- Fast programming
1) Named constructor generate shot – cut key use the mac window + n.
Second press (Named constructor)
2) When UI create step following.
3) Generic more use.
4) Create common widget.
5) Last is very important your API structure. For example: Firebase implement, Google login, Facebook login, API calling, get the image etc.
6) not use more build() method. You can use Extention method.
binding not create GetView
“ProductController” not found. You need to call “Get.put(ProductController())” or “Get.lazyPut(()=>ProductController())”
Binding class create step:
extends Bindings
class ProductBinding extends Bindings{
@override
void dependencies() {
Get.put(ProductController());
}
}
GetMaterialApp Add
GetMaterialApp(
initialRoute: “/”,
getPages: [ GetPage(name: “/”, page: () => HomePage(), binding: ProductBinding(),)])
initialRoute: find the name from getPages.
getPages: Collection of pages.
GetX update model class value or not
class ProductResponse { String id, productName, productDescription; double price; ProductResponse( {this.id, this.productName, this.productDescription, this.price, int quantity = 0, bool isFavourite = false}) { this.setQuantity(quantity); this.setIsFavourite(isFavourite); } RxInt quantity = RxInt(0); setQuantity(int value) => quantity.value = value; RxBool isFavourite = RxBool(false); setIsFavourite(bool value) => isFavourite.value = value; }
GetX update model class value
class ProductResponse { String id, productName, productDescription; double price; ProductResponse( {this.id, this.productName, this.productDescription, this.price, int quantity = 0, bool isFavourite = false}) { this.setQuantity(quantity); this.setIsFavourite(isFavourite); } RxInt quantity = RxInt(0); setQuantity(int value) => quantity.value = value; RxBool isFavourite = RxBool(false); setIsFavourite(bool value) => isFavourite.value = value; }
GetX using search (filter)
- Create temp list:
var productTempList = []; Store data
productTempList = productData;
filter logic getx in flutter:
productNameSearch(String name) { //Empty then all data store in productList if (name.isEmpty) { productList.value = productTempList; } else { //Search must be tempList using productList.value = productTempList .where((element) => element.productName.toLowerCase().contains(name.toLowerCase())) .toList(); } }
Getx using total Amount get
var totalAmount = RxDouble(0);
totalAmount.value = productList.fold(0, (previous, current) => previous + current.price * current.quantity.value);
- previous one type of store previous total amount.
- price * quantity

product_binding.dart
import 'package:get/get.dart'; import '../controller/product_controller.dart'; class ProductBinding extends Bindings{ @override void dependencies() { Get.put<ProductController>(ProductController()); } }
product_controller.dart
aimport 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:listview_shopping_setstate/model/product_response.dart'; class ProductController extends GetxController { TextEditingController searchController = TextEditingController(); var productList = <ProductResponse>[].obs; var productTempList = <ProductResponse>[]; var totalAmount = RxDouble(0); @override void onInit() { super.onInit(); //Get data var productData = _productData(); //Store data productList.value = productData; productTempList = productData; } favourite(ProductResponse productResponse) { productResponse.isFavourite.value = !productResponse.isFavourite.value; } quantityAdd(ProductResponse productResponse) { productResponse.quantity++; _totalAmountGet(); } quantityMinus(ProductResponse productResponse) { if (productResponse.quantity.value > 0) { productResponse.quantity--; _totalAmountGet(); } } productNameSearch(String name) { if (name.isEmpty) { productList.value = productTempList; } else { productList.value = productTempList .where((element) => element.productName.toLowerCase().contains(name.toLowerCase())) .toList(); } } _totalAmountGet() { totalAmount.value = productList.fold(0, (previous, current) => previous + current.price * current.quantity.value); } } _productData() => [ ProductResponse( id: '1', productName: 'Apple', productDescription: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ', price: 250), ProductResponse( id: '2', productName: 'Banana', productDescription: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ', price: 40), ProductResponse( id: '3', productName: 'Mango', productDescription: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ', price: 100), ];
product_response.dart
import 'package:get/get.dart'; class ProductResponse { String id, productName, productDescription; double price; ProductResponse( {this.id, this.productName, this.productDescription, this.price, int quantity = 0, bool isFavourite = false}) { this.setQuantity(quantity); this.setIsFavourite(isFavourite); } RxInt quantity = RxInt(0); setQuantity(int value) => quantity.value = value; RxBool isFavourite = RxBool(false); setIsFavourite(bool value) => isFavourite.value = value; }
Package UI>Pages
product_page.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../controller/product_controller.dart'; import '../widget/text_field_search.dart'; class ProductPage extends GetView<ProductController> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('ListView Shopping GetX')), bottomNavigationBar: Container( padding: EdgeInsets.all(10), color: Colors.grey.withOpacity(0.1), height: 40, child: Align( alignment: Alignment.bottomRight, child: Obx( () => Text('Total Amount: ${controller.totalAmount}')))), body: Column(children: [ TextFieldSearch( textEditingController: controller.searchController, isPrefixIconVisible: true, onChanged: controller.productNameSearch), Expanded( child: Obx(() => ListView(shrinkWrap: true, children: [ ...controller.productList .map((e) => Card( child: Padding( padding: EdgeInsets.all(5), child: Column(children: [ Row(children: [ CircleAvatar(radius: 25), SizedBox(width: 7), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(e.productName, style: TextStyle( fontSize: 16, color: Colors.black)), SizedBox(height: 3), Text('Rs. ${e.price}', style: TextStyle( fontSize: 16, color: Colors.black)), SizedBox(height: 3), Text('${e.productDescription}', style: TextStyle( fontSize: 14, color: Colors.black54)), ])), IconButton( onPressed: () => controller.favourite(e), icon: Obx(() => Icon( e.isFavourite.value ? Icons.favorite : Icons.favorite_border, color: Colors.grey))) ]), SizedBox(height: 8), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ InkWell( borderRadius: BorderRadius.circular(15.0), child: CircleAvatar( backgroundColor: Colors.blue .withOpacity(0.1), radius: 15, child: Text('-', style: TextStyle( color: Colors.blue))), onTap: () => controller.quantityMinus(e)), SizedBox(width: 5), Text('${e.quantity.value}'), SizedBox(width: 5), InkWell( borderRadius: BorderRadius.circular(15.0), child: CircleAvatar( backgroundColor: Colors.blue .withOpacity(0.1), radius: 15, child: Text('+', style: TextStyle( color: Colors.blue))), onTap: () => controller.quantityAdd(e)) ]) ])))) .toList() ]))) ])); } }
Package UI>Widget
text_field_search.dart
import 'package:flutter/material.dart'; class TextFieldSearch extends StatelessWidget { final TextEditingController textEditingController; final ValueChanged<String> onChanged; final VoidCallback callBackClear, callBackPrefix, callBackSearch; final isPrefixIconVisible; final String hintText; TextFieldSearch( {@required this.textEditingController, @required this.onChanged, this.callBackClear, this.isPrefixIconVisible = false, this.callBackSearch, this.callBackPrefix, this.hintText = 'Search'}); @override Widget build(BuildContext context) { return Container( height: 40, margin: EdgeInsets.all(10), child: TextField( controller: textEditingController, onChanged: onChanged, textInputAction: TextInputAction.search, textCapitalization: TextCapitalization.words, style: TextStyle(fontSize: 15), decoration: InputDecoration( border: InputBorder.none, isCollapsed: true, contentPadding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 12.0), prefixIcon: isPrefixIconVisible ? IconButton( icon: Icon(Icons.search, size: 20, color: Colors.blue), onPressed: callBackPrefix) : null, enabledBorder: OutlineInputBorder( borderRadius: const BorderRadius.all(const Radius.circular(10.0)), borderSide: BorderSide(color: Colors.black)), focusedBorder: OutlineInputBorder( borderRadius: const BorderRadius.all(const Radius.circular(10.0)), borderSide: BorderSide(color: Colors.blue)), filled: true, hintStyle: TextStyle( fontSize: 15, color: Colors.black54, textBaseline: TextBaseline.alphabetic), hintText: hintText, fillColor: Colors.grey.withOpacity(0.1)))); } }
main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'ui/page/product_page.dart'; import 'binding/product_binding.dart'; void main() { //STATUS BAR SET SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarBrightness: Brightness.light, statusBarIconBrightness: Brightness.light, )); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return GetMaterialApp( theme: ThemeData(primarySwatch: Colors.blue), initialRoute: "/", getPages: [ GetPage( name: "/", page: () => ProductPage(), binding: ProductBinding()), ]); } }
The flutter tutorial is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application
For more information about Flutter. visit www.fluttertutorial.in