Skip to content

pub地址:https://pub.dev/packages/provider

ViewModel

记得调用notifyListeners设置监听

groovy
import 'package:flutter/cupertino.dart';
import 'package:flutter_base/bean/banner_bean_entity.dart';
import 'package:flutter_base/net/http_helper.dart';
import 'package:flutter_base/net/http_util.dart';

import '../../bean/home_list_entity.dart';

///
/// @DIR_PATH:lib/viewmodel/home
/// @TIME:2024/5/4 14:37
/// @AUTHOR:starr
///
class HomeViewModel with ChangeNotifier {
  List<BannerBeanData>? bannerList;
  List<HomeItemData>? homeList;

  Future getBannerData() async {
    var json = await HttpUtil().get(HttpHelper.BANNER);
    if (json != null) {
      bannerList = BannerBeanEntity.fromJson(json).data;
    } else {
      bannerList = [];
    }
  }

  notifyListeners();

  Future getHomeListData() async {
    var json = await HttpUtil().get(HttpHelper.HOME_LIST);
    if (json != null) {
      homeList = HomeListEntity.fromJson(json).data?.datas;
    } else {
      homeList = [];
    }
    notifyListeners();
  }
}

Widget

ChangeNotifierProvider的本质就是一个Widget, create:接收一个泛型函数, child:就是我们需要做状态管理的Widget

groovy
 @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeViewModel>(
        create: (context) => homeViewModel,
        child: SafeArea(
          child: SingleChildScrollView(
            child: Column(children: [
              //第一部分:banner
              _banner(),
              //第二部分:ListView
              _listView(),
            ]),
          ),
        ));
  }

Consumer

groovy
Widget _listView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return ListView.builder(
          itemBuilder: (context, index) {
            return _listItemView(vm.homeList?[index]);
          },
          // 优化
          shrinkWrap: true,
          // 禁止滑动
          physics: NeverScrollableScrollPhysics(),
          itemCount: vm.homeList?.length ?? 0);
    });
  }