|
| 1 | +--- |
| 2 | +slug: /concepts/custom-code/common-examples |
| 3 | +title: Common Examples |
| 4 | +description: Learn about the common custom code examples and use it directly in your project. |
| 5 | +tags: [Custom Actions, Custom Code] |
| 6 | +sidebar_position: 6 |
| 7 | +keywords: [FlutterFlow, Custom Actions, Customizations, Flutter, Dart, Pub.dev, Examples] |
| 8 | +--- |
| 9 | + |
| 10 | +# Common Code Examples |
| 11 | + |
| 12 | +The custom code feature in FlutterFlow allows you to extend functionality by accessing generated classes and modifying global variables like App States and FlutterFlow themes. This guide covers common scenarios where you can leverage custom code to enhance your project by working directly with data models and other resources within your code. |
| 13 | + |
| 14 | +### Accessing FlutterFlow Generated Classes |
| 15 | + |
| 16 | +Most custom FlutterFlow classes are prefixed with `FF<ClassName>` or `FlutterFlow<ClassName>`. If you need to access these classes in your custom code, simply type "FF" or "FlutterFlow" in the code editor to locate them easily. |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +### Returning Component from Custom Widget |
| 21 | + |
| 22 | +In a **[Custom Widget](custom-widgets.md)**, you can integrate a previously built **[FlutterFlow Component](../../resources/ui/components/intro-components.md)** directly, saving you from recreating child content in code. For example, if you’re building a Custom Widget to display custom dialog boxes or bottom sheets using a package from |
| 23 | +[pub.dev](custom-code.md#pubdev), you can simply return an existing Component created on the canvas, rather than coding the content from scratch. |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +### Accessing FlutterFlow Theme in Custom Widget |
| 29 | + |
| 30 | +When building custom widgets, you often need to style parts of the widget, such as setting colors. Instead of using hardcoded color values, you can directly access the **FlutterFlow Theme**. This theme provides consistent styling across your app and reflects colors set by you or your project developer. |
| 31 | + |
| 32 | +To access theme colors in your custom widget, use the `FlutterFlowTheme.of(context)` method. This allows you to retrieve any theme color, such as the **primary color, accent color**, or **background color**, ensuring that your custom widget aligns with the app’s overall theme. |
| 33 | + |
| 34 | +Here’s an example of how to use the primary color from FlutterFlow Theme in a custom widget: |
| 35 | + |
| 36 | +:::tip[Imports] |
| 37 | +Ensure you import `import '../flutter_flow/flutter_flow_theme.dart';` when accessing `FlutterFlowTheme` in your custom widgets. |
| 38 | +::: |
| 39 | + |
| 40 | + |
| 41 | +```js |
| 42 | +class CustomButton extends StatefulWidget { |
| 43 | + final String label; |
| 44 | + |
| 45 | + CustomButton({required this.label}); |
| 46 | + |
| 47 | + @override |
| 48 | + _CustomButtonState createState() => _CustomButtonState(); |
| 49 | +} |
| 50 | + |
| 51 | +class _CustomButtonState extends State<CustomButton> { |
| 52 | + bool isPressed = false; |
| 53 | + |
| 54 | + void toggleButton() { |
| 55 | + setState(() { |
| 56 | + isPressed = !isPressed; |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + @override |
| 61 | + Widget build(BuildContext context) { |
| 62 | + return ElevatedButton( |
| 63 | + style: ElevatedButton.styleFrom( |
| 64 | + primary: isPressed |
| 65 | + ? FlutterFlowTheme.of(context).primary // Primary color when pressed |
| 66 | + : FlutterFlowTheme.of(context).secondaryBackground, // Default color |
| 67 | + onPrimary: FlutterFlowTheme.of(context).secondaryText, // Text color |
| 68 | + ), |
| 69 | + onPressed: toggleButton, |
| 70 | + child: Text( |
| 71 | + widget.label, |
| 72 | + style: FlutterFlowTheme.of(context).bodyText1, // Themed text style |
| 73 | + ), |
| 74 | + ); |
| 75 | + } |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | + |
| 80 | +### Manipulating AppState from Custom Code |
| 81 | + |
| 82 | +In FlutterFlow, you can access or update AppState directly from the Action Flow Editor. However, certain scenarios may require you to access or modify AppState within custom code for more control over the operation flow. The FFAppState class also provides additional helper functions to manipulate AppState variables. Let’s look at some examples: |
| 83 | + |
| 84 | +:::tip[Imports] |
| 85 | +Ensure you import `import '../../flutter_flow/flutter_flow_util.dart';` when accessing `FFAppState` in custom code resources. |
| 86 | +::: |
| 87 | + |
| 88 | +- **Accessing AppState in Custom Code** |
| 89 | + |
| 90 | +```js |
| 91 | + |
| 92 | +Future getCartItems() async { |
| 93 | + // Retrieve the current cart items from AppState |
| 94 | + final currentCartItems = FFAppState().cartItems; |
| 95 | + print('Current Cart Items: $currentCartItems'); |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +- **Updating AppState Values in Custom Code** |
| 100 | + |
| 101 | +```js |
| 102 | +Future enableDarkMode() async { |
| 103 | + // Enable dark mode in AppState |
| 104 | + FFAppState().update(() { |
| 105 | + FFAppState().enableDarkMode = true; |
| 106 | + }); |
| 107 | + print('Dark mode enabled'); |
| 108 | +} |
| 109 | +``` |
| 110 | + |
| 111 | +- **Modifying a List in AppState Using Helper Functions** |
| 112 | + |
| 113 | +The `FFAppState` class offers a variety of helper functions to easily manage list variables in AppState. For a detailed overview of this generated class, check out **[this guide](../../generated-code/ff-app-state.md#managing-appstatelist)**. Here’s some examples of how to use these helper functions to modify an AppState list variable: |
| 114 | + |
| 115 | +```js |
| 116 | +Future addLocation(LatLng value) async { |
| 117 | + // Add a new location to the LatLng list |
| 118 | + FFAppState().addToLatLngList(value); |
| 119 | +} |
| 120 | + |
| 121 | +Future removeLocation(LatLng value) async { |
| 122 | + // Remove a specific location from the LatLng list |
| 123 | + FFAppState().removeFromLatLngList(value); |
| 124 | +} |
| 125 | + |
| 126 | +Future removeLocationAtIndex(int index) async { |
| 127 | + // Remove a location at a specific index from the LatLng list |
| 128 | + FFAppState().removeAtIndexFromLatLngList(index); |
| 129 | +} |
| 130 | + |
| 131 | +Future updateLocationAtIndex(int index, LatLng Function(LatLng) updateFn) async { |
| 132 | + // Update a location at a specific index in the LatLng list |
| 133 | + FFAppState().updateLatLngListAtIndex(index, updateFn); |
| 134 | +} |
| 135 | + |
| 136 | +Future insertLocationAtIndex(int index, LatLng value) async { |
| 137 | + // Insert a new location at a specific index in the LatLng list |
| 138 | + FFAppState().insertAtIndexInLatLngList(index, value); |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | + |
| 143 | +### Manipulate Custom Data Types |
| 144 | +When you create a custom data type in FlutterFlow, it **[generates a corresponding `<Name>Struct` class](../../generated-code/custom-data-type-gen.md)**. In FlutterFlow's custom code, you can create new instances of such data types, pass instances back into an action, or manipulate and retrieve information from existing objects. Here are some examples to help illustrate working with an example `ProductStruct` class. |
| 145 | + |
| 146 | +#### Example 1: Creating a new Instance of `ProductStruct` |
| 147 | +To create a new `ProductStruct` instance, initialize it with the required properties: |
| 148 | + |
| 149 | +```js |
| 150 | +// Create a new instance of ProductStruct |
| 151 | +final newProduct = ProductStruct( |
| 152 | + productId: '123', |
| 153 | + name: 'Example Product', |
| 154 | + description: 'A sample product description.', |
| 155 | + category: 'Electronics', |
| 156 | + subCategory: 'Mobile Phones', |
| 157 | + price: PriceStruct(amount: 299.99, currency: 'USD'), |
| 158 | + sizes: ['Small', 'Medium', 'Large'], |
| 159 | + colors: [ColorsStruct(colorName: 'Red', colorHex: '#FF0000')], |
| 160 | + images: [ImagesStruct(thumbnail: 'https://example.com/image.jpg')], |
| 161 | + stockStatus: StockStatusStruct(xs: 0, small: 2), |
| 162 | + reviews: [ReviewsStruct(rating: 4, comment: 'Great product!')], |
| 163 | +); |
| 164 | + |
| 165 | +``` |
| 166 | + |
| 167 | +#### Example 2: Accessing Properties of an Existing `ProductStruct` object |
| 168 | + |
| 169 | +If you have an existing `ProductStruct` object (e.g., retrieved from a list of products), you can access its properties or return specific values back to the calling Action. Let's assume you have an Action that calls a Custom Action to retrieve a field value from the provided `ProductStruct` object. |
| 170 | + |
| 171 | +- **Returning a Single Field from ProductStruct** |
| 172 | + |
| 173 | +This function retrieves and returns the product's name. The return type is `String?` to account for the possibility of a null value. |
| 174 | +```js |
| 175 | +// Function to return the product name from a ProductStruct instance |
| 176 | +String? getProductName(ProductStruct product) { |
| 177 | + // Access and return the product name |
| 178 | + return product.name; |
| 179 | +} |
| 180 | +``` |
| 181 | +- **Returning a List of Review Comments from ProductStruct** |
| 182 | +
|
| 183 | +This function retrieves a list of review comments from the reviews field in the `ProductStruct`. The return type is `List<String>` as it returns a list of comments (or an empty list if there are no reviews). |
| 184 | +
|
| 185 | +```js |
| 186 | +// Function to return a list of review comments from a ProductStruct instance |
| 187 | +List<String> getProductReviewComments(ProductStruct product) { |
| 188 | + // Check if reviews are present and return a list of review comments |
| 189 | + return product.reviews?.map((review) => review.comment ?? '').toList() ?? []; |
| 190 | +} |
| 191 | +``` |
| 192 | +
|
| 193 | +#### Example 3: Modifying Properties of an Existing `ProductStruct` Object |
| 194 | +You can also modify the properties of an existing `ProductStruct` object. This can be helpful if you want to update a field before saving the data back to Firebase or passing it into an action. |
| 195 | +
|
| 196 | +- **Simple Property Modification** |
| 197 | +In this example, we’ll modify a single property, like `productId`, of an existing `ProductStruct` object. This example is straightforward and demonstrates how to update a basic field in the object. |
| 198 | +
|
| 199 | +```js |
| 200 | +// Function to update the product ID of a ProductStruct instance |
| 201 | +Future updateProductId(ProductStruct product, String newProductId) { |
| 202 | + // Update the product ID with the new value |
| 203 | + product.productId = newProductId; |
| 204 | +} |
| 205 | +``` |
| 206 | +
|
| 207 | +- **Complex Property Modification - Nested Object Update** |
| 208 | +In this more complex example, we’ll modify a nested property within the `ProductStruct`, such as updating the price (which itself is a `PriceStruct` object). This shows how to update a property that itself contains multiple fields. |
| 209 | +
|
| 210 | +```js |
| 211 | +// Function to update the price of a ProductStruct instance |
| 212 | +Future updateProductPrice(ProductStruct product, double newAmount, String currency) { |
| 213 | +// Check if price is not null |
| 214 | + if (product.price != null) { |
| 215 | + // Update only the amount field |
| 216 | + product.price!.amount = newAmount; |
| 217 | + } else { |
| 218 | + // If price is null, optionally initialize it if needed |
| 219 | + product.price = PriceStruct( |
| 220 | + amount: newAmount, |
| 221 | + currency: currency, |
| 222 | + ); |
| 223 | + } |
| 224 | +} |
| 225 | +``` |
| 226 | +
|
| 227 | +- **Complex Property Modification - Updating a List Property** |
| 228 | +In this example, we’ll add new items to a list property, like adding new review comments to the `reviews` list in `ProductStruct`. This example shows how to work with a list of nested objects. |
| 229 | +
|
| 230 | +```js |
| 231 | +Future addNewReviews(ProductStruct product) { |
| 232 | + product.reviews ??= []; // Initialize the reviews list if it's null |
| 233 | + product.reviews!.addAll([ |
| 234 | + ReviewStruct(rating: 5, comment: 'Excellent product!'), |
| 235 | + ReviewStruct(rating: 4, comment: 'Good quality, but a bit expensive.'), |
| 236 | + ReviewStruct(rating: 3, comment: 'Satisfactory, meets expectations.'), |
| 237 | + ]); |
| 238 | +} |
| 239 | +``` |
| 240 | +
|
| 241 | +or if the new list of reviews are being provided to the Custom Action, then: |
| 242 | +
|
| 243 | +```js |
| 244 | +Future addDynamicReviews(ProductStruct product, List<ReviewStruct> newReviews) { |
| 245 | + product.reviews ??= []; // Initialize the reviews list if it's null |
| 246 | + product.reviews!.addAll(newReviews); // Add the new reviews |
| 247 | +} |
| 248 | + |
| 249 | +``` |
0 commit comments