Flutter provider使用案例

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => WeatherInfo(),
      child: Scaffold(
        appBar: AppBar(
          title: Text('title'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Heading(),
              Content(),
            ],
          ),
        ),
        floatingActionButton: MyButton(),
      ),
    );
  }
}

class Heading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var weatherInfo = Provider.of<WeatherInfo>(context);

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(weatherInfo.temperatureType),
    );
  }
}

class Content extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Consumer<WeatherInfo>(
        builder: (context, weatherInfo, _) =>
            Text(weatherInfo.temperatureVal.toString()),
      ),
    );
  }
}

class MyButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var weatherInfo = Provider.of<WeatherInfo>(context);
    return FloatingActionButton(
      backgroundColor: Colors.red,
      onPressed: () {
        String newWeatherType =
            weatherInfo.temperatureType == '摄氏度' ? '花适度' : '摄氏度';
        weatherInfo.temperatureType = newWeatherType;
        int newTemp = weatherInfo.temperatureVal == 25 ? 100 : 125;
        weatherInfo.temperatureVal=newTemp;
      },
      tooltip: '改变温度类型',
      child: Text(weatherInfo.temperatureType),
    );
  }
}

WeatherInfo.dart

import 'package:flutter/foundation.dart';

class WeatherInfo with ChangeNotifier {
  String _tempType = '摄氏度';
  int _temperatureVal = 25;

  int get temperatureVal => _temperatureVal;

  String get temperatureType => _tempType;

  set temperatureVal(int newTemp) {
    _temperatureVal = newTemp;
    notifyListeners();
  }

  set temperatureType(String newType) {
    _tempType = newType;
    notifyListeners();
  }
}