Flutter状态State管理 Provider MultiProvider Consumer

1.引包

dependencies:
    provider: ^6.0.1

MultiProvider:可以调用多个provider数据
Consumer:可以做到局部加载数据,也可以同表widget里面同时改动或者绑定多个provider数据
比如:Consumer(),Consumer2(),Consumer3(),Consumer4(),Consumer5(),Consumer6()

Flutter状态State管理 Provider MultiProvider Consumer_第1张图片

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


//import 'package:dio/'
main() => runApp(MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (ctx) => FristCounterProvider()),
        ChangeNotifierProvider(create: (ctx) => SecondCounterProvider()),
      ],
      child: MyApp(),
    ));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Provider"),
        ),
        body: FristPage(),
        floatingActionButton: setFloatingActionButton());
  }
}

Widget setFloatingActionButton() {
  return Consumer2<FristCounterProvider, SecondCounterProvider>(
    builder: (contextx, fristProvider, secondProvider, child) {
      return FloatingActionButton(
        child: child,
        onPressed: () {
          fristProvider.counter += 1;
          secondProvider.counter += 1;
        },
      );
    },
    child:Icon(Icons.add),
  );
}

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

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          child: Center(
            child: Consumer<FristCounterProvider>(
                builder: (ctx, cunterPro, child) {
              return Text("当前Frist计数:${cunterPro.counter}",style: TextStyle(fontSize: 30),);
            }),
          ),
        ),
        Container(
          child: Center(
            child: Consumer<SecondCounterProvider>(
                builder: (ctx, cunterPro, child) {
              return Text("当前Second计数:${cunterPro.counter}",style: TextStyle(fontSize: 30),);
            }),
          ),
        )
      ],
    );
  }
}



class FristCounterProvider extends ChangeNotifier {
  int _counter = 50;
  int get counter {
    return _counter;
  }

  set counter(int value) {
    _counter = value;
    notifyListeners();
  }
}

class SecondCounterProvider extends ChangeNotifier {
  int _counter = 100;
  int get counter {
    return _counter;
  }

  set counter(int value) {
    _counter = value;
    notifyListeners();
  }
}

你可能感兴趣的:(Flutter,flutter,html5)