0
点赞
收藏
分享

微信扫一扫

Flutter中GetX的用法(路由管理)

前言 正如Get官方介绍,GetX 是 Flutter 上的一个轻量且强大的解决方案:高性能的状态管理、智能的依赖注入和便捷的路由管理。GetX 有3个基本原则:

性能: GetX 专注于性能和最小资源消耗。

    效率: GetX 的语法非常简捷,并保持了极高的性能,能极大缩短你的开发时长。

    结构: GetX 可以将界面、逻辑、依赖和路由之间低耦合,逻辑更清晰,代码更容易维护。

    这篇文章主要是介绍下GetX的用法。

一.安装 目前get最新的版本是4.6.6。安装方式如下:

dependencies: get: ^4.6.6

二.从一个计时器开始 但我们创建一个flutter工程的时候,系统会生成一个计时器的示例代码,代码大致如下(我删除了部分注释代码):

import 'package:flutter/material.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
 
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
 
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

主要功能是点击+按钮,每次计时器的个数+1.点击按钮之后,调用setState方法刷新_counter变量。

下面我们看一下如何使用getx来实现上述的功能:

    第一步:把系统的MaterialApp改成GetMaterialApp:

void main() => runApp(GetMaterialApp(home: Home()));

第二步:创建业务类,我们把_counter变量放在Controller类中:

class Controller extends GetxController{ var counter = 0.obs; increment() => counter++; }

第三步:使用StatelessWidget代替StatefulWidget,节省下内存。修改之后的完整代码如下:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class Controller extends GetxController{
  var counter = 0.obs;
  incrementCounter()=>counter++;
}
 
class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
 
  @override
  Widget build(BuildContext context) {
    final Controller controller = Get.put(Controller());
 
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Obx(() => Text(
              '${controller.counter}',
              style: Theme.of(context).textTheme.headlineMedium,
            )),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          controller.incrementCounter();
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

三.Getx路由管理

1.普通路由导航

1.导航到新的页面

        假如我们有一个新页面NextScreenPage,代码如下

import 'package:flutter/material.dart';
 
class NextScreenPage extends StatelessWidget {
  const NextScreenPage({super.key});
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("新页面"),
      ),
      body: Container(
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

从当前页面跳转到NextScreenPage页面,代码如下:

Get.to(()=>NextScreen());

2.关闭SnackBars、Dialogs、BottomSheets或任何你通常会用Navigator.pop(context)关闭的东西 还是以上面的代码为例,我们添加一个返回按钮,点击返回按钮的时候,回到当前页面。主需要在按钮的点击事件中添加如下代码即可:

Get.back();

NextScreenPage页面完整代码如下:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
 
class NextScreenPage extends StatelessWidget {
  const NextScreenPage({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("新页面"),
      ),
      body: Center(
        child: ElevatedButton(onPressed: (){
          Get.back();
        }, child: const Text("返回上一个页面")),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

举报

相关推荐

0 条评论