简体   繁体   English

如何使用getx controller,绑定,getview?

[英]How to use getx controller, binding,getview?

I trying to create small project with getx, I have 3 file's get view,getxcontroller,binding and then when I'm running I get issue like this:我试图用 getx 创建小项目,我有 3 个文件的获取视图、getxcontroller、绑定,然后当我运行时我遇到这样的问题:

Unhandled Exception: "IncrementController" not found.未处理的异常:找不到“IncrementController”。 You need to call "Get.put(IncrementController())" or "Get.lazyPut(()=>IncrementController())"您需要调用“Get.put(IncrementController())”或“Get.lazyPut(()=>IncrementController())”

so did i wrong about getx flow step?那么我对 getx 流程步骤有误吗? let's checkit my code below:让我们在下面检查我的代码:

main.dart主要.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/controller.dart';
import 'package:get/get.dart';

void main() {
  runApp(GetMaterialApp(
    home: HomePage(),
  ));
}

class HomePage extends GetView<IncrementController> {
  final IncrementController _controller = Get.find<IncrementController>();
  @override
  Widget build(BuildContext context) {
    //display increment with getx
    return Scaffold(
      appBar: AppBar(
        title: Text('GetX'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${_controller.increment}',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _controller.incrementFun,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

controller controller

import 'package:get/get_rx/get_rx.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_getx_widget.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';

class IncrementController extends GetxController {
  //create increment with getx
  RxInt _increment = 0.obs;
  //get increment
  int get increment => _increment.value;

  //create increment functiion with getx
  void incrementFun() => _increment.value++;
}

binding捆绑

import 'package:flutter_application_1/controller.dart';
import 'package:get/get.dart';

class IncrementBinding implements Bindings {
  @override
  void dependencies() {
    // TODO: implement dependencies
    //create controller with getx
    Get.lazyPut<IncrementController>(() => IncrementController());
  }
}

You need to set the initial binding inside the MaterialApp or GetMaterialApp like this:您需要在 MaterialApp 或 GetMaterialApp 中设置初始绑定,如下所示:

    GetMaterialApp(
      initialBinding: IncrementBinding(),
      home: HomeOage(),
    );

you need to call IncrementBinding() method in your route befor going to HomePage.在转到主页之前,您需要在路由中调用 IncrementBinding() 方法。 just like this: Get.to(HomePage(),binding:IncrementBinding() );就像这样: Get.to(HomePage(),binding:IncrementBinding() ); Or this: GetMaterialApp( initialBinding: IncrementBinding(), home: HomePage(), );或者这样: GetMaterialApp( initialBinding: IncrementBinding(), home: HomePage(), ); or if you use this way you can call just like this: GetPage( name: Routes.homePage enter code, page: () => HomePage(), binding: IncrementBinding(), ), `或者如果你使用这种方式,你可以像这样调用: GetPage( name: Routes.homePage enter code, page: () => HomePage(), binding: IncrementBinding(), ), `

You have to add initialBinding parameter in the GetMaterialApp() widget, and in the UI class where you use GetView , You have to wrap the column or the whole scaffold with a Obx() or GetX() widget, because in the controller class you have used Rx and .obs .您必须在 GetMaterialApp() 小部件中添加initialBinding参数,并在您使用GetView的 UI class 中添加参数,您必须使用Obx()GetX()小部件包装列或整个脚手架,因为在 controller class 中,您使用过Rx.obs

You can see this example, these some classes from one of my projects:你可以看到这个例子,这些来自我的一个项目的一些类:

main function:主要 function:

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: Binding(),
      debugShowCheckedModeBanner: false,
      home: const HomePage(),
    );
  }
}

Binding class:绑定class:

class Binding extends Bindings {
  @override
  void dependencies() {
    Get.put(() => AuthController());
    Get.lazyPut(() => HomePageController());
  }
}

Controller class: Controller class:

class Database extends GetxController {
  static Database instance = Database();

  final CollectionReference userCollectionRef =
      FirebaseFirestore.instance.collection('Users');

  List<SubscriberModel> subscriberModel = <SubscriberModel>[].obs;

  List<UserModel> userModel = <UserModel>[].obs;
}

The UI class:用户界面 class:

class SubscriberInfo extends StatelessWidget {
  const SubscriberInfo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      SubscriberController controller = Get.put(SubscriberController());
      return Scaffold(
        backgroundColor: AppColors.whiteColor,
        body: SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          scrollDirection: Axis.vertical,
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.only(top: Dimensions.height50),
                child: AddTextField(
                  controller: controller.searchController,
                  type: TextInputType.text,
                  label: 'Search subscriber'.tr,
                  maxLength: 25,
                  autoFocus: false,
                  secureText: false,
                  onTap: () {},
                  onEditComplete: () {
                    FocusScope.of(context).unfocus();
                  },
                  onChange: controller.onSearching,
                ),
              ),
              ListView.builder(
                physics: const BouncingScrollPhysics(),
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                itemCount: controller.filteredSubscribers.length,
                itemBuilder: (context, index) {
                  final item = controller.filteredSubscribers[index];
                  return buildSubInfo(
                    context: context,
                    name: item.firstName,
                    lastName: item.lastName,
                    father: item.father,
                    subType: item.subscriptionType,
                    counterNo: item.counterNumber,
                    date: item.date,
                    edit: () {
                      controller.editSubscriberWidget(
                        id: item.id,
                      );
                    },
                    delete: () {
                      controller.deleteSubscriberWidget(
                        id: item.id,
                      );
                    },
                    onClick: () {},
                  );
                },
              ),
            ],
          ),
        ),
      );
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM