【Flutter】Provider之HelloWorld

pubspec.yaml:

provider: ^5.0.0

main.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: [
          Provider<FirstPageServiceButtonsProvider>(create: (_) => FirstPageServiceButtonsProvider()),
        ],
        child: MaterialApp(...);
  }
}

Provider class:

import 'package:flutter/material.dart';

class FirstPageServiceButtonsProvider with ChangeNotifier {
  int _page = 0;

  void changePage(page) {
    _page = page;
    notifyListeners();
  }

  get page => _page;
}

修改数据:

context.read<FirstPageServiceButtonsProvider>().changePage(index);

监听数据变化:

int page = context.watch<FirstPageServiceButtonsProvider>().page;
上一篇:ios 应用程序之间的跳转(内置程序的实现)


下一篇:kubernetes-3 k8s集群中的生命周期