【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(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().changePage(index);

监听数据变化:

int page = context.watch().page;

你可能感兴趣的:(Flutter,dart,flutter,provider,helloworld)