Flutter实战项目-第四篇 页面路由、provider状态管理

概要

  • 页面路由配置
  • provider

一、路由配置

创建router.dart用于管理所有的路由,然后再main.dart MaterialApp中注册路由。

router.dart中第一个routeName="/",即是默认打开的页面

import './view/login/login.dart';
class JDRouter {
  static final routes = {
    Login.routeName: (context) => const Login()
  };
}

main.dart

import 'package:flutter/material.dart';
import 'router.dart';
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: JDRouter.routes,
    );
  }
}

二、状态管理

        provider官方推荐的状态管理,类似Vuex和reduce之类。其可以全局注册,也可以局部注册,用户可根据自己的实际需求选择注册方式。因为状态的改变会触发build,所以用户使用是应当避免反复的build消耗。provider本身支持监听多个,但是也是有数量限制,具体可以查阅官方资料。当前只是介绍了最常用的情况。

        2.1全局注册

        创建文件global.notifier.dart

import 'package:flutter/material.dart';

class GlobalNotifier with ChangeNotifier{
  //底部导航栏按钮状态
  int menuIndex =0;
  void increment(int param){
    menuIndex = param;
    notifyListeners();
  }
}

在main.dart中注册

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'router.dart';
import 'store/global.notifier.dart';
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<GlobalNotifier>(create: (_)=>GlobalNotifier()),
      ],
      child:MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        routes: JDRouter.routes,
      )
    );
  }
}

页面中使用监听及更新值

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../store/global.notifier.dart';
class Login extends StatefulWidget {
  /// 登录页面
  const Login({Key? key}) : super(key: key);
  static const routeName = '/';
  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(20),
      child: Consumer<GlobalNotifier>(
        builder: (_, globalNotifier,child){
          return Column(
            children:[
              Text('${globalNotifier.menuIndex}'),
              TextButton(
                onPressed: (){
                  globalNotifier.increment(10);
                },
                child: Text("更新值")
              )
            ]
          );
        }
      )
    );
  }
}

代码中获取值/设置

Provider.of<GlobalNotifier>(context).menuIndex

Provider.of<GlobalNotifier>(context).menuIndex

///需在initsate之后使用
Provider.of<GlobalNotifier>(context,listen: false).increment(10);

多个监听时

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../store/global.notifier.dart';
import '../../store/login/login.notifier.dart';
class Login extends StatefulWidget {
  /// 登录页面
  const Login({Key? key}) : super(key: key);
  static const routeName = '/';
  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(20),
      child: Consumer2<GlobalNotifier,LoginNotifier>(
        builder: (_, globalNotifier,loginNotifier,child){
          return Column(
            children:[
              Text('${globalNotifier.menuIndex}${loginNotifier.name}'),
              TextButton(
                onPressed: (){
                  globalNotifier.increment(10);
                  loginNotifier.increment('JavonHuang');
                },
                child: Text("更新值")
              )
            ]
          );
        }
      )
    );
  }
}

2.2局部注册

        通过ChangeNotifierProvider可以使实现局部注册

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../store/global.notifier.dart';
import '../../store/login/login.notifier.dart';
class Login extends StatefulWidget {
  /// 登录页面
  const Login({Key? key}) : super(key: key);
  static const routeName = '/';
  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return  ChangeNotifierProvider<LoginNotifier>(
      create: (_) => LoginNotifier(),
      child:Container(
      color: Colors.white,
      padding: EdgeInsets.all(20),
      child: Consumer<LoginNotifier>(
        builder: (_,loginNotifier,child){
          return Column(
            children:[
              Text('${loginNotifier.name}'),
              TextButton(
                onPressed: (){
                  // globalNotifier.increment(10);
                  loginNotifier.increment('JavonHuang');
                },
                child: Text("更新值")
              )
            ]
          );
        }
      )
    ) ,
    );
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值