flutter 如何使用getx控制器,绑定,getview?

wgx48brx  于 2023-01-18  发布在  Flutter
关注(0)|答案(3)|浏览(401)

我试图用getx创建小项目,我有3个文件的获取视图,getxcontroller,绑定,然后当我运行时,我得到这样的问题:
未处理的异常:未找到"增量控制器"。需要调用"Get. put(增量控制器())"或"Get. lazyPut(()=〉增量控制器())"
那么我对getx流程步骤理解错了吗?让我们检查一下下面的代码:
main.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),
      ),
    );
  }
}

控制器

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++;
}

装订

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());
  }
}
6bc51xsx

6bc51xsx1#

您需要在MaterialApp或GetMaterialApp内部设置初始绑定,如下所示:

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

pftdvrlh2#

你需要在你的路由中调用IncrementBinding()方法才能转到主页.就像这样:Get.to(HomePage(),binding:IncrementBinding() );或者这个:GetMaterialApp( initialBinding: IncrementBinding(), home: HomePage(), );或者如果你用这种方式你可以这样调用:GetPage( name: Routes.homePage输入代码,页码:()=〉主页(),绑定:增量绑定(),),'

wqsoz72f

wqsoz72f3#

您必须在GetMaterialApp()小部件和使用GetView的UI类中添加initialBinding参数,必须使用Obx()GetX()小部件 Package 列或整个支架,因为在控制器类中使用了Rx.obs
你可以看到这个例子,这些类来自我的一个项目:
主要功能:

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(),
    );
  }
}

绑定类:

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

控制器类:

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;
}

UI类:

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: () {},
                  );
                },
              ),
            ],
          ),
        ),
      );
    });
  }
}

相关问题