Flutter学习笔记之Provider 5.0.0入门级使用

Provider使用:
1.创建CounterModel(等同于get中GetController)

class CounterModel with ChangeNotifier {
     
  int _counter = 0;
  int get counter => _counter;

  void increment() {
     
    _counter++;
    notifyListeners();
  }
}

2.注册(相当于get中Get.put)

class MyApp extends StatelessWidget {
     
  const MyApp({
     Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
     
    return MultiProvider(
        providers: [ChangeNotifierProvider(create: (_) => CounterModel())],
        child: MaterialApp(
          home: MyHomePage(),
        ));
  }
}

3.使用


class MyHomePage extends StatelessWidget {
     
  const MyHomePage({
     Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
     
    return Scaffold(
      appBar: AppBar(
        title: const Text('Provider'),
      ),
      body: Center(
        child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('${context.watch().counter}')
              ]),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read<CounterModel>().increment(),
        child: const Icon(Icons.add),
      ),
    );
  }
}

你可能感兴趣的:(Flutter)