Simple GetX example


Sure! Below is a simple Flutter application using the GetX state management library to display "Hello, World!". This example includes setting up GetX and using a controller to manage the state.

### Step 1: Add Dependencies

Add the GetX package to your `pubspec.yaml` file:

```yaml
dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
```

### Step 2: Create the Controller

Create a controller class to manage the state. This class will extend `GetxController`.

```dart
// lib/controllers/hello_controller.dart
import 'package:get/get.dart';

class HelloController extends GetxController {
  var message = 'Hello, World!'.obs;

  void changeMessage(String newMessage) {
    message.value = newMessage;
  }
}
```

### Step 3: Create the View

Create the main view that uses the controller.

```dart
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controllers/hello_controller.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Hello World App',
      home: HelloWorldPage(),
    );
  }
}

class HelloWorldPage extends StatelessWidget {
  final HelloController helloController = Get.put(HelloController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GetX Hello World'),
      ),
      body: Center(
        child: Obx(() {
          return Text(
            helloController.message.value,
            style: TextStyle(fontSize: 24),
          );
        }),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          helloController.changeMessage('Hello, GetX!');
        },
        child: Icon(Icons.refresh),
      ),
    );
  }
}
```

### Explanation

1. **Dependencies:** The GetX package is added to the `pubspec.yaml` file.
2. **Controller:** A `HelloController` class is created to manage the message state. It has a method to change the message.
3. **View:** The main view (`HelloWorldPage`) uses the `HelloController`. The `Obx` widget is used to reactively update the UI when the `message` value changes. A floating action button is provided to change the message when pressed.

This code will display "Hello, World!" in the center of the screen. When the floating action button is pressed, it changes the message to "Hello, GetX!".


Contact us for software training, education or development










 

Post a Comment

0 Comments

Me